package com.telit.firecommand.service.impl;

import cn.hutool.core.collection.CollUtil;
import cn.hutool.core.collection.CollectionUtil;
import cn.hutool.core.convert.Convert;
import cn.hutool.core.date.DatePattern;
import cn.hutool.core.date.DateUtil;
import cn.hutool.core.map.MapUtil;
import cn.hutool.core.util.ObjectUtil;
import cn.hutool.core.util.StrUtil;
import cn.hutool.json.JSONUtil;
import com.alibaba.fastjson.JSON;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.toolkit.ChainWrappers;
import com.github.xiaolyuh.annotation.Cacheable;
import com.github.xiaolyuh.annotation.SecondaryCache;
import com.github.xiaolyuh.support.CacheMode;
import com.telit.android.dto.SimpleFireAlarmDTO;
import com.telit.android.feign.RemoteAndroidService;
import com.telit.common.constant.DictTypeConstants;
import com.telit.common.dto.LongitudeAndLatitudeDTO;
import com.telit.common.entity.DataReturn;
import com.telit.common.entity.PageData;
import com.telit.common.exception.ForestBaseException;
import com.telit.common.util.*;
import com.telit.dispose.vo.dispose.PlatTableVO;
import com.telit.dispose.vo.resourceManagement.DictVO;
import com.telit.firecommand.dao.*;
import com.telit.firecommand.dto.*;
import com.telit.firecommand.entity.*;
import com.telit.firecommand.listener.FireExcludeProp;
import com.telit.firecommand.service.FireQueryService;
import com.telit.firecommand.service.UserInfoService;
import com.telit.firecommand.service.WebSocketPushMsgLogService;
import com.telit.firecommand.vo.ResourceSimpLevelMinVO;
import com.telit.upms.feign.RemoteUpmsService;
import com.telit.upms.vo.MicroSysUserAllInfoVo;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.jetbrains.annotations.NotNull;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.CollectionUtils;

import java.math.BigDecimal;
import java.util.*;
import java.util.concurrent.TimeUnit;
import java.util.stream.Collectors;

import static com.telit.common.service.ParamsCheckService.*;


/**
 * @author zhouyu
 * @description 火情查询实现类
 */
@Service
@Transactional(rollbackFor = Exception.class)
@RequiredArgsConstructor
@Slf4j
public class FireQueryServiceImpl implements FireQueryService {

    @Value("${fire.limitDistance}")
    private String limitDistance;

    @Value("${fire.cameraLimitDistance}")
    private String cameraLimitDistance;

    /*@Value("${fire.excludeDistrict}")
    private List<String> excludeDistrict;
*/

    private final FireExcludeProp fireExcludeProp;
    @Autowired
    private CommFireAlarmDao commFireAlarmDao;

//    @Autowired
//    private CommCameraInfoDao commCameraInfoDao;

    @Autowired
    private CommSatelliteInfoDao commSatelliteInfoDao;

//    @Autowired
//    private UavFeignClient uavFeignClient;

    @Autowired
    private CommHistoryFireDao commHistoryFireDao;

    @Autowired
    private CommFireHandleDao fireHandleDao;

//    @Autowired
//    private EmergencyDrillInfoDao emergencyDrillInfoDao;

    @Autowired
    private AppTaskFeedbackDao appTaskFeedbackDao;

    @Autowired
    private FileUploadLogDao fileUploadLogDao;

//    @Autowired
//    private DictDataService dictDataService;

    @Autowired
    private UserInfoService userInfoService;

    @Autowired
    private GeoXzqhXiangDao geoXzqhXiangDao;

    @Autowired
    private FireSmsPushLogDao fireSmsPushLogDao;

    @Autowired
    private FireReportSuperiorLogDao fireReportSuperiorLogDao;

    @Autowired
    private WebSocketPushMsgLogService webSocketPushMsgLogService;

    @Autowired
    private BusinessTableDao businessTableDao;

    @Autowired
    private GeoXzqhCunDao geoXzqhCunDao;

    private final CommCountrysideSortDao commCountrysideSortDao;

    private final RemoteUpmsService upmsFeignClient;
    private final RemoteAndroidService androidFeignClient;

    private final DictMapper dictMapper;


    @Override
    public boolean queryIsExist(Long fireId) {
        int count = commFireAlarmDao.queryIsExist(fireId);
        return count > 0;
    }

    /**
     * 流转流程：待接警 -> 待核实 -> 待处置 -> 处置中 -> 已处置
     */
    @Override
    public FireDetailDTO queryDetailById(Long fireId) {
        CommFireAlarm commFireAlarm = commFireAlarmDao.selectByPrimaryKey(fireId);
        if (commFireAlarm == null) {
            return null;
        }

        FireDetailDTO fireDetailDTO = new FireDetailDTO();
        fireDetailDTO.setIsAction(commFireAlarm.getAction());
        String status = commFireAlarm.getStatus();
        fireDetailDTO.setCurrentStatus(status);
        //任务信息按照下达人员进行展示；人员排序规则：按照第一次反馈时间顺序排序
        List<AppTaskFeedback> appTaskFeedbacksInfo = appTaskFeedbackDao.queryFireFeedback(commFireAlarm.getId()).stream()
                .sorted(Comparator.comparing(AppTaskFeedback::getFeedbackTime,Comparator.nullsFirst(Date::compareTo)))
                //根据任务下发人去重
                .collect(Collectors.collectingAndThen(Collectors.toCollection(() -> new TreeSet<>(Comparator.comparing(AppTaskFeedback :: getIssueTaskId))), ArrayList::new));
        List<Long> personIds = appTaskFeedbacksInfo.stream().map(AppTaskFeedback::getIssueTaskId).distinct().collect(Collectors.toList());
        Map<Long, String> idForestNameMapping = userInfoService.findAndConvertUserInfoByIds(personIds);
        List<Map<String,String>> forestList = new ArrayList<>();
        personIds.forEach(e ->{
            if(StringUtils.isNotEmpty(idForestNameMapping.get(e))){
                Map<String, String> forestMap = new HashMap<>();
                forestMap.put("personId",Convert.toStr(e));
                forestMap.put("personName",idForestNameMapping.get(e));
                forestList.add(forestMap);
            }
        });
        fireDetailDTO.setPersonInfo(forestList);
        switch (status) {
            // 待接警
            case "1":
                //填充待接警信息
                fillPendingReceiveAlarm(fireDetailDTO, commFireAlarm);
                break;
            // 待核实
            case "2":
                // 1.填充待接警信息
                fillPendingReceiveAlarm(fireDetailDTO, commFireAlarm);
                // 2.填充待核实信息
                fillPendingVerify(fireDetailDTO, commFireAlarm);
                //20220424 根据需求追加部分指标信息
                final List<AppTaskFeedback> appTaskFeedbacks = appTaskFeedbackDao.queryFireFeedback(commFireAlarm.getId());
                //获取任务
                final Map<String, String> taskMap = buildTrackType();
                //2022-05-19 对于旧代码中 获取 用户信息地方进行变更 -----fixed by yzx------start
               /* final List<TaskFeedbackInfoDTO> taskFeedbackInfoDTOList = appTaskFeedbacks.stream().map(d -> {
                    final TaskFeedbackInfoDTO dto = new TaskFeedbackInfoDTO();
                    //增加反馈内容
                    dto.setFeedBackContent(d.getContent());
                    dto.setAssignTaskTime(d.getAssignTaskTime());
                    dto.setFeedbackTime(d.getFeedbackTime());
                    dto.setFireType(d.getFireType());
                    dto.setMediaUrlList(MediaUrlUtils.handleMediaUrlToList(d.getMediaUrl()));
                    dto.setResource(d.getResource());
                    //下述代码保留
                    if ("1".equals(d.getResource())) {
                        //护林员
                        dto.setForestKeeperName(d.getFeedbackPersonName());
                    } else if ("2".equals(d.getResource())) {
                        //飞手
                        dto.setUavControlerName(d.getFeedbackPersonName());
                    } else if ("3".equals(d.getResource())) {
                        //无人机
                        Long feedbackPersonId = d.getFeedbackPersonId();
                        String uavName = appTaskFeedbackDao.queryUavName(d.getTaskId(), feedbackPersonId);
                        dto.setUavName(uavName);
                    } else {
                        //说明还没开始巡护
                        //查巡护类型 ，脏数据没有的话，默认
                        final String type = MapUtil.getStr(taskMap, d.getType());
                        //13 和 null 代表巡护， 14 代表巡航
                        final Map<String, Object> user = (Map<String, Object>) upmsFeignClient.getUserDetail(d.getIssueTaskId()).getData();
                        if (StrUtil.isEmpty(type) || StrUtil.equals("13", type)) {
                            dto.setForestKeeperName(Convert.toStr(user.get("realName")));
                        } else {
                            dto.setUavControlerName(Convert.toStr(user.get("realName")));
                        }
                    }
                    return dto;
                }).collect(Collectors.toList());*/
                final List<Long> ids = appTaskFeedbacks.stream().map(AppTaskFeedback::getIssueTaskId).collect(Collectors.toList());
            //    final Map<Long, String> idNameMapping = userInfoService.findAndConvertUserInfoByIds(ids);
                //根据产品需求，任务反馈根据护林员点击展示，以下注释
//                final List<TaskFeedbackInfoDTO> taskFeedbackInfoDTOList = appTaskFeedbacks.stream().map(d -> {
//                    final TaskFeedbackInfoDTO dto = new TaskFeedbackInfoDTO();
//                    //增加反馈内容
//                    dto.setFeedBackContent(d.getContent());
//                    dto.setAssignTaskTime(d.getAssignTaskTime());
//                    dto.setFeedbackTime(d.getFeedbackTime());
//                    dto.setFireType(d.getFireType());
//                    dto.setMediaUrlList(MediaUrlUtils.handleMediaUrlToList(d.getMediaUrl()));
//                    dto.setResource(d.getResource());
//                    //下述代码保留
//                    if ("1".equals(d.getResource())) {
//                        //护林员
//                        dto.setForestKeeperName(d.getFeedbackPersonName());
//                    } else if ("2".equals(d.getResource())) {
//                        //飞手
//                        dto.setUavControlerName(d.getFeedbackPersonName());
//                    } else if ("3".equals(d.getResource())) {
//                        //无人机
//                        Long feedbackPersonId = d.getFeedbackPersonId();
//                        String uavName = appTaskFeedbackDao.queryUavName(d.getTaskId(), feedbackPersonId);
//                        dto.setUavName(uavName);
//                    } else {
//                        //说明还没开始巡护
//                        //查巡护类型 ，脏数据没有的话，默认
//                        final String type = MapUtil.getStr(taskMap, d.getType());
//                        //13 和 null 代表巡护， 14 代表巡航
//                        if (StrUtil.isEmpty(type) || StrUtil.equals("13", type)) {
//                            dto.setForestKeeperName(ObjectUtil.defaultIfNull(idNameMapping.get(d.getIssueTaskId()), StrUtil.EMPTY));
//                        } else {
//                            dto.setUavControlerName(ObjectUtil.defaultIfNull(idNameMapping.get(d.getIssueTaskId()), StrUtil.EMPTY));
//                        }
//                    }
//                    return dto;
//                }).collect(Collectors.toList());
//                //2022-05-19 对于旧代码中 获取 用户信息地方进行变更 -----fixed by yzx------start
//                fireDetailDTO.getPendingVerify().setTaskFeedbackInfoDTOS(taskFeedbackInfoDTOList);
                break;
            //  误报
            case "6":
                // 1.填充待接警信息
                fillPendingReceiveAlarm(fireDetailDTO, commFireAlarm);
                // 2.填充待核实信息
                fillPendingVerify(fireDetailDTO, commFireAlarm);
                // 3.填充误报信息
                fillFakeFire(fireDetailDTO, commFireAlarm);
                break;
            //  待处置
            case "3":
                // 1.填充待接警信息
                fillPendingReceiveAlarm(fireDetailDTO, commFireAlarm);
                // 2.填充待核实信息
                fillPendingVerify(fireDetailDTO, commFireAlarm);
                // 3.填充待处置信息
                fillPendingDispose(fireDetailDTO, commFireAlarm);
                break;
            // 处置中
            case "4":
                // 1.填充待接警信息
                fillPendingReceiveAlarm(fireDetailDTO, commFireAlarm);
                // 2.填充待核实信息
                fillPendingVerify(fireDetailDTO, commFireAlarm);
                // 3.填充待处置信息
                fillPendingDispose(fireDetailDTO, commFireAlarm);
                // 4.填充处理中信息
                fillUnderDispose(fireDetailDTO, commFireAlarm);
                break;
            // 已处置
            case "5":
                // 1.填充待接警信息
                fillPendingReceiveAlarm(fireDetailDTO, commFireAlarm);
                // 2.填充待核实信息
                fillPendingVerify(fireDetailDTO, commFireAlarm);
                // 3.填充待处置信息
                fillPendingDispose(fireDetailDTO, commFireAlarm);
                // 4.填充处理中信息
                fillUnderDispose(fireDetailDTO, commFireAlarm);
                // 5.填充已处理信息
                fillHasDispose(fireDetailDTO, commFireAlarm);
                break;
        }
        return fireDetailDTO;
    }

    @Override
    public List<TaskFeedbackInfoDTO>  queryTaskFeedbackInfo(Long fireId, Long personId) {
        final List<AppTaskFeedback> appTaskFeedbacks = appTaskFeedbackDao.queryFireFeedbackByid(fireId, personId);
        final List<TaskFeedbackInfoDTO> taskFeedbackInfoDTOList = appTaskFeedbacks.stream().map(d -> {
            final TaskFeedbackInfoDTO dto = new TaskFeedbackInfoDTO();
            //增加反馈内容
            dto.setFeedBackContent(d.getContent());
            dto.setAssignTaskTime(d.getAssignTaskTime());
            dto.setFeedbackTime(d.getFeedbackTime());
            dto.setFireType(d.getFireType());
            dto.setPersonId(d.getIssueTaskId());
            dto.setMediaUrlList(MediaUrlUtils.handleMediaUrlToList(d.getMediaUrl()));
            return dto;
        }).collect(Collectors.toList());
        return taskFeedbackInfoDTOList;
    }

    /**
     * 临时处理 子任务间的关系
     *
     * @return value-> parentValue;
     */
    @SuppressWarnings("all")
    private Map<String, String> buildTrackType() {
        final DataReturn dr = androidFeignClient.searchNoPageForFeign();
        final List<Map<String, String>> treeMap = (List<Map<String, String>>) Convert.toList(dr.getData());
        final Map<String, String> convert = treeMap.stream().collect(Collectors.toMap(m -> m.get("value"), m -> m.get("parentValue")));
        return convert;
    }

    /**
     * 填充 "待接警" 信息
     */
    private void fillPendingReceiveAlarm(FireDetailDTO fireDetailDTO, CommFireAlarm commFireAlarm) {
        PendingReceiveAlarm pendingReceiveAlarm = new PendingReceiveAlarm();
        pendingReceiveAlarm.setResource(commFireAlarm.getResource());
        pendingReceiveAlarm.setAddress(commFireAlarm.getDetailAddress());
        pendingReceiveAlarm.setDistrictName(commFireAlarmDao.queryAddressNameByCode(commFireAlarm.getDistrictCode()));
        pendingReceiveAlarm.setLongitude(commFireAlarm.getLongitude());
        pendingReceiveAlarm.setLatitude(commFireAlarm.getLatitude());
        pendingReceiveAlarm.setContent(commFireAlarm.getContent());
        pendingReceiveAlarm.setFinderName(commFireAlarm.getFinderName());
        pendingReceiveAlarm.setReportTime(commFireAlarm.getFindTime());
        String imageUrl = commFireAlarm.getImageUrl();
        if (StringUtils.isNotBlank(imageUrl)) {
            pendingReceiveAlarm.setImageUrl(MediaUrlUtils.handleMediaUrlToList(imageUrl));
        }
        fireDetailDTO.setPendingReceiveAlarm(pendingReceiveAlarm);
    }

    /**
     * 填充 "待核实" 信息
     */
    private void fillPendingVerify(FireDetailDTO fireDetailDTO, CommFireAlarm commFireAlarm) {
        PendingVerify pendingVerify = new PendingVerify();
        Long recieverId = commFireAlarm.getRecieverId();
        MicroSysUserAllInfoVo sysUserVo = userInfoService.getUserInfo(recieverId);
        if (sysUserVo != null) {
            String username = sysUserVo.getRealName();
            // 单位名称
            String unit = sysUserVo.getDeptName();
            pendingVerify.setReceiveName(username);
            pendingVerify.setReceiveUnit(unit);
        }
        pendingVerify.setReceiveTime(commFireAlarm.getRecieveTime());
        fireDetailDTO.setPendingVerify(pendingVerify);
    }

    /**
     * 填充 "误报" 信息
     */
    private void fillFakeFire(FireDetailDTO fireDetailDTO, CommFireAlarm commFireAlarm) {
        FakeFire fakeFire = new FakeFire();
        fakeFire.setComfirmFakeTime(commFireAlarm.getConfirmTime());
        Long confirmId = commFireAlarm.getConfirmId();
        MicroSysUserAllInfoVo sysUserVo = userInfoService.getUserInfo(confirmId);
        if (sysUserVo != null) {
            String username = sysUserVo.getRealName();
            String unit = sysUserVo.getDeptName();
            fakeFire.setComfirmFakePerson(username);
            fakeFire.setConfirmUnit(unit);
        }
        //app端确认信息
        ConfirmFireDTO confirmFireDTO = new ConfirmFireDTO();
        String imageUrl = commFireAlarm.getAppImageUrl();
        if (StringUtils.isNotBlank(imageUrl)) {
            confirmFireDTO.setFilesUrl(MediaUrlUtils.handleMediaUrlToList(imageUrl));
        }
        confirmFireDTO.setFaketype(commFireAlarm.getFaketype());
        confirmFireDTO.setDescription(commFireAlarm.getFakeDescription());
        fakeFire.setConfirmFireDTO(confirmFireDTO);
        fakeFire.setFakeDescription(commFireAlarm.getFakeDescription());
        fireDetailDTO.setFakeFire(fakeFire);
    }

    /**
     * 填充 “待处置” 信息
     */
    private void fillPendingDispose(FireDetailDTO fireDetailDTO, CommFireAlarm commFireAlarm) {
        //根据产品需求，任务反馈根据护林员点击展示，以下注释
//        List<AppTaskFeedback> appTaskFeedbacks = appTaskFeedbackDao.queryFireFeedback(commFireAlarm.getId());
//        List<TaskFeedbackInfoDTO> taskFeedbackInfoDTOS = new ArrayList<>(appTaskFeedbacks.size());
//        appTaskFeedbacks.forEach(e -> {
//            TaskFeedbackInfoDTO taskFeedbackInfoDTO = new TaskFeedbackInfoDTO();
//            //增加反馈内容
//            taskFeedbackInfoDTO.setFeedBackContent(e.getContent());
//            taskFeedbackInfoDTO.setAssignTaskTime(e.getAssignTaskTime());
//            taskFeedbackInfoDTO.setFeedbackTime(e.getFeedbackTime());
//            taskFeedbackInfoDTO.setFireType(e.getFireType());
//            String url = e.getMediaUrl();
//            if (StringUtils.isNotBlank(url)) {
//                List<String> array = JSON.parseArray(url, String.class);
//                List<String> temp = new ArrayList<>(array.size());
//                array.forEach(a -> {
//                    String path = MinioUtils.previewImg(a);
//                    temp.add(path);
//                });
//                taskFeedbackInfoDTO.setMediaUrlList(temp);
//            }
//            String resource = e.getResource();
//            taskFeedbackInfoDTO.setResource(resource);
//            if ("1".equals(resource)) {
//                //护林员
//                taskFeedbackInfoDTO.setForestKeeperName(e.getFeedbackPersonName());
//            } else if ("2".equals(resource)) {
//                //飞手
//                taskFeedbackInfoDTO.setUavControlerName(e.getFeedbackPersonName());
//            } else if ("3".equals(resource)) {
//                //无人机
//                Long feedbackPersonId = e.getFeedbackPersonId();
//                String uavName = appTaskFeedbackDao.queryUavName(e.getTaskId(), feedbackPersonId);
//                taskFeedbackInfoDTO.setUavName(uavName);
//            }
//            taskFeedbackInfoDTOS.add(taskFeedbackInfoDTO);
//        });
//        if (fireDetailDTO.getPendingVerify() != null) {
//            fireDetailDTO.getPendingVerify().setTaskFeedbackInfoDTOS(taskFeedbackInfoDTOS);
//        }
        PendingDispose pendingDispose = new PendingDispose();
        Long confirmId = commFireAlarm.getConfirmId();
        MicroSysUserAllInfoVo sysUserVo = userInfoService.getUserInfo(confirmId);
        if (sysUserVo != null) {
            String username = sysUserVo.getRealName();
            String unit = sysUserVo.getDeptName();
            pendingDispose.setConfirmName(username);
            pendingDispose.setConfirmUnit(unit);
        }
        pendingDispose.setConfirmFireTime(commFireAlarm.getConfirmTime());
        List<String> pendingPersons = fireSmsPushLogDao.querySendPerson(commFireAlarm.getId(), 0);
        List<FirePushMsgDTO> pendingFirePushMsgDTOS = new ArrayList<>(pendingPersons.size());
        pendingPersons.forEach(person -> {
            List<FireSmsPushLog> fireSmsPushLogs = fireSmsPushLogDao.queryAllByFireId(commFireAlarm.getId(), 0, person);
            FirePushMsgDTO pendingFirePushMsgDTO = new FirePushMsgDTO();
            List<FirePushMsgObj> pendingFirePushMsgObjs = new ArrayList<>(fireSmsPushLogs.size());
            fireSmsPushLogs.forEach(e -> {
                Date pushTime = e.getPushTime();
                pendingFirePushMsgDTO.setSendTime(pushTime);
                pendingFirePushMsgDTO.setSendName(e.getSendPerson());
                FirePushMsgObj firePushMsgObj = new FirePushMsgObj();
                firePushMsgObj.setPushName(e.getPushName());
                firePushMsgObj.setUnit(e.getPushUnit());
                pendingFirePushMsgObjs.add(firePushMsgObj);
            });
            pendingFirePushMsgDTO.setFirePushMsgObjs(pendingFirePushMsgObjs);
            pendingFirePushMsgDTOS.add(pendingFirePushMsgDTO);
        });
        pendingDispose.setFirePushMsgDTOs(pendingFirePushMsgDTOS);
        FireReportSuperiorLog pendingFireReportSuperiorLog = fireReportSuperiorLogDao.queryByFireId(commFireAlarm.getId(), 3);
        if (pendingFireReportSuperiorLog != null) {
            pendingDispose.setReportTime(pendingFireReportSuperiorLog.getReportTime());
            pendingDispose.setReportPersonName(pendingFireReportSuperiorLog.getReportPersonName());
            pendingDispose.setReportPersonUnit(pendingFireReportSuperiorLog.getReportPersonUnit());
        }
        //app端确认信息
        ConfirmFireDTO confirmFireDTO = new ConfirmFireDTO();
        confirmFireDTO.setDescription(commFireAlarm.getFakeDescription());
        String imageUrl = commFireAlarm.getAppImageUrl();
        if (StringUtils.isNotBlank(imageUrl)) {
            confirmFireDTO.setFilesUrl(MediaUrlUtils.handleMediaUrlToList(imageUrl));
        }
        pendingDispose.setConfirmFireDTO(confirmFireDTO);
        fireDetailDTO.setPendingDispose(pendingDispose);
    }

    /**
     * 填充 “处理中” 信息
     */
    private void fillUnderDispose(FireDetailDTO fireDetailDTO, CommFireAlarm commFireAlarm) {
        UnderDispose underDispose = new UnderDispose();
        Long managementId = commFireAlarm.getManagementId();
        MicroSysUserAllInfoVo sysUserVo = userInfoService.getUserInfo(managementId);
        if (sysUserVo != null) {
            String username = sysUserVo.getRealName();
            String unit = sysUserVo.getDeptName();
            underDispose.setConfirmDisposeName(username);
            underDispose.setConfirmDisposeUnit(unit);
        }
        underDispose.setConfirmDisposeTime(commFireAlarm.getManagementTime());
        List<String> underPersons = fireSmsPushLogDao.querySendPerson(commFireAlarm.getId(), 1);
        List<FirePushMsgDTO> underFirePushMsgDTOS = new ArrayList<>(underPersons.size());
        underPersons.forEach(person -> {
            List<FireSmsPushLog> fireSmsPushLogs = fireSmsPushLogDao.queryAllByFireId(commFireAlarm.getId(), 1, person);
            FirePushMsgDTO underFirePushMsgDTO = new FirePushMsgDTO();
            List<FirePushMsgObj> pendingFirePushMsgObjs = new ArrayList<>(fireSmsPushLogs.size());
            fireSmsPushLogs.forEach(e -> {
                Date pushTime = e.getPushTime();
                underFirePushMsgDTO.setSendTime(pushTime);
                underFirePushMsgDTO.setSendName(e.getSendPerson());
                FirePushMsgObj firePushMsgObj = new FirePushMsgObj();
                firePushMsgObj.setPushName(e.getPushName());
                firePushMsgObj.setUnit(e.getPushUnit());
                pendingFirePushMsgObjs.add(firePushMsgObj);
            });
            underFirePushMsgDTO.setFirePushMsgObjs(pendingFirePushMsgObjs);
            underFirePushMsgDTOS.add(underFirePushMsgDTO);
        });
        underDispose.setFirePushMsgDTOs(underFirePushMsgDTOS);
        FireReportSuperiorLog underFireReportSuperiorLog = fireReportSuperiorLogDao.queryByFireId(commFireAlarm.getId(), 4);
        if (underFireReportSuperiorLog != null) {
            underDispose.setReportTime(underFireReportSuperiorLog.getReportTime());
            underDispose.setReportPersonName(underFireReportSuperiorLog.getReportPersonName());
            underDispose.setReportPersonUnit(underFireReportSuperiorLog.getReportPersonUnit());
        }
        //app端确认信息
        ConfirmFireDTO confirmFireDTO = new ConfirmFireDTO();
        String imageUrl = commFireAlarm.getAppImageUrl();
        if (StringUtils.isNotBlank(imageUrl)) {
            confirmFireDTO.setFilesUrl(MediaUrlUtils.handleMediaUrlToList(imageUrl));
        }
        confirmFireDTO.setDescription(commFireAlarm.getFakeDescription());
        underDispose.setConfirmFireDTO(confirmFireDTO);
        fireDetailDTO.setUnderDispose(underDispose);
    }

    /**
     * 填充 “已处理” 信息
     */
    private void fillHasDispose(FireDetailDTO fireDetailDTO, CommFireAlarm commFireAlarm) {
        HasDispose hasDispose = new HasDispose();
        Long finishId = commFireAlarm.getFinishId();
        MicroSysUserAllInfoVo sysUserVo = userInfoService.getUserInfo(finishId);
        if (sysUserVo != null) {
            String username = sysUserVo.getRealName();
            String unit = sysUserVo.getDeptName();
            hasDispose.setFinishName(username);
            hasDispose.setFinishUnit(unit);
        }
        //app端确认信息
        ConfirmFireDTO confirmFireDTO = new ConfirmFireDTO();
        String imageUrl = commFireAlarm.getAppImageUrl();
        if (StringUtils.isNotBlank(imageUrl)) {
            confirmFireDTO.setFilesUrl(MediaUrlUtils.handleMediaUrlToList(imageUrl));
        }
        confirmFireDTO.setDescription(commFireAlarm.getFakeDescription());
        hasDispose.setConfirmFireDTO(confirmFireDTO);
        hasDispose.setFinishTime(commFireAlarm.getFinishTime());
        fireDetailDTO.setHasDispose(hasDispose);
    }

    @Override
//    @Cacheable(value = "firecommand:fire:queryAllFireByCondition",depict = "条件查询所有火情,默认查询全部")
    public Object queryAllFireByCondition(String status, String startTime, String endTime, String districtCode, String source, String isEmergencyDrill, String fireLevel, Integer page, Integer rows) {
//        if (districtCode != null) {
        //在具体条件查询中排查错误发现存在districtCode传递空字符串的情况，改为以下判断
        if (StrUtil.isNotEmpty(districtCode)) {
            districtCode = districtCode + "%";
        }
        if (rows != null && page != null) {
            IPage<CommFireAlarm> appTaskStatusPage = new Page<>(page, rows);
            IPage<CommFireAlarm> pages = commFireAlarmDao.queryAllFireByCondition(appTaskStatusPage, status, startTime,
                    endTime, districtCode, source, isEmergencyDrill, fireLevel, null, null, null);
            List<CommFireAlarm> records = pages.getRecords();
            List<CommFireAlarm> commFireAlarms = this.setExtInfo(records);
            pages.setRecords(commFireAlarms);
            PageData<Object> pageData = new PageData<>();
            pageData.setDatas(pages.getRecords());
            pageData.setCount((int) pages.getTotal());
            pageData.setCurrent((int) pages.getCurrent());
            pageData.setSize((int) pages.getSize());
            return pageData;
        } else {
            List<CommFireAlarm> commFireAlarms = commFireAlarmDao.queryAllFireByConditionNoPage(status, startTime, endTime, districtCode, source, isEmergencyDrill, fireLevel);
            List<CommFireAlarm> commFireAlarm = this.setExtInfo(commFireAlarms);
            Map<String, Object> map = new HashMap<>(2);
            map.put("data", commFireAlarm);
            map.put("total", commFireAlarm.size());
            return map;
        }
    }

    @Override
    public Object queryAllFireForAppByCondition(String status, String startTime, String endTime, String districtCode, String source, String isEmergencyDrill, String fireLevel, Integer page, Integer rows) {
       /* if (districtCode != null) {
            districtCode = districtCode + "%";
        }*/

        if (StringUtils.isNotEmpty(districtCode)) {
            districtCode = districtCode + "%";
        }
        if (rows != null && page != null) {
            IPage<CommFireAlarm> appTaskStatusPage = new Page<>(page, rows);
            IPage<CommFireAlarm> pages = commFireAlarmDao.queryAllFireForAppByCondition(appTaskStatusPage, status, startTime, endTime, districtCode, source, isEmergencyDrill, fireLevel);
            List<CommFireAlarm> records = pages.getRecords();
            List<CommFireAlarm> commFireAlarms = this.setExtInfo(records);
            pages.setRecords(commFireAlarms);
            PageData<Object> pageData = new PageData<>();
            pageData.setDatas(pages.getRecords());
            pageData.setCount((int) pages.getTotal());
            pageData.setCurrent((int) pages.getCurrent());
            pageData.setSize((int) pages.getSize());
            return pageData;
        } else {
            List<CommFireAlarm> commFireAlarms = commFireAlarmDao.queryAllFireByConditionNoPage(status, startTime, endTime, districtCode, source, isEmergencyDrill, fireLevel);
            List<CommFireAlarm> commFireAlarm = this.setExtInfo(commFireAlarms);
            Map<String, Object> map = new HashMap<>(2);
            map.put("data", commFireAlarm);
            map.put("total", commFireAlarm.size());
            return map;
        }
    }

    @Override
    public PageData<Object> queryTelephoneAlarm() {
        IPage<CommFireAlarm> page = new Page<>(1, 10);
        IPage<CommFireAlarm> pages = commFireAlarmDao.queryTelephoneAlarm(page);
        List<CommFireAlarm> records = pages.getRecords();
        List<CommFireAlarm> commFireAlarms = this.setExtInfo(records);
        pages.setRecords(commFireAlarms);
        PageData<Object> pageData = new PageData<>();
        pageData.setDatas(pages.getRecords());
        pageData.setCount((int) pages.getTotal());
        pageData.setCurrent((int) pages.getCurrent());
        pageData.setSize((int) pages.getSize());
        return pageData;
    }

    @Override
   // @Cacheable(value = "firecommand:fire:queryTelephoneAlarmByDistrictCode",depict = "分页查询电话接警")
    public PageData<Object> queryTelephoneAlarmByDistrictCode(String districtCode) {
        IPage<CommFireAlarm> page = new Page<>(1, 10);
//        IPage<CommFireAlarm> pages = commFireAlarmDao.queryTelephoneAlarmByDistrictCode(page, districtCode);
        //注释掉上一行代码，因为数据库中需要模糊查询，需要传递“%”
        IPage<CommFireAlarm> pages = commFireAlarmDao.queryTelephoneAlarmByDistrictCode(page, districtCode + "%");
        List<CommFireAlarm> records = pages.getRecords();
        List<CommFireAlarm> commFireAlarms = this.setTelephoneAlarmExtInfo(records);
        pages.setRecords(commFireAlarms);
        PageData<Object> pageData = new PageData<>();
        pageData.setDatas(pages.getRecords());
        pageData.setCount((int) pages.getTotal());
        pageData.setCurrent((int) pages.getCurrent());
        pageData.setSize((int) pages.getSize());
        return pageData;
    }

    @Override
   // @Cacheable(value = "firecommand:fire:queryAllTelephoneAlarm",depict = "条件查询所有电话接警")
    public PageData<Object> queryAllTelephoneAlarm(String startTime, String endTime, Integer page, Integer rows,String districtCode) {
        //获取当前用户的区级或者街道级行政区划
     //   String villageDistrictCode = "JwtTokenUtils.getVillageDistrictCode()";

        IPage<CommFireAlarm> iPage = new Page<>(page, rows);
        IPage<CommFireAlarm> pages = commFireAlarmDao.queryAllTelephoneAlarm(iPage, startTime, endTime, districtCode);
        List<CommFireAlarm> records = pages.getRecords();
        List<CommFireAlarm> commFireAlarms = this.setExtInfo(records);
        pages.setRecords(commFireAlarms);
        PageData<Object> pageData = new PageData<>();
        pageData.setDatas(pages.getRecords());
        pageData.setCount((int) pages.getTotal());
        pageData.setCurrent((int) pages.getCurrent());
        pageData.setSize((int) pages.getSize());
        return pageData;
    }

    @Override
    public Map<Object, Object> queryAllStatusNumber( String districtCode) {
        List<Map<String, Object>> list = commFireAlarmDao.queryAllStatusNumber(districtCode);
        Map<Object, Object> map = new HashMap<>(6);
        //6种状态
        map.put("1", 0);
        map.put("2", 0);
        map.put("3", 0);
        map.put("4", 0);
        map.put("5", 0);
        map.put("6", 0);
        list.forEach(a -> {
            Object status = a.get("status");
            Object count = a.get("count");
            map.put(status, count);
        });
        return map;
    }

    @Override
    public Object queryLeftFireInfo(String districtCode) {
        Integer num = commFireAlarmDao.queryUnFinishFireNum(districtCode);
        if (num <= 10) {
            //未处置完成火情小于等于10 按状态和报警时间倒排
            IPage<CommFireAlarm> page = new Page<>(1, 10);
            IPage<CommFireAlarm> pages = commFireAlarmDao.queryLeftFireInfoOrderByTimeAndStatus(page, districtCode);
            List<CommFireAlarm> records = pages.getRecords();
            List<CommFireAlarm> commFireAlarms = this.setFireExtInfo(records);
            pages.setRecords(commFireAlarms);
            PageData<Object> pageData = new PageData<>();
            pageData.setDatas(pages.getRecords());
            pageData.setCount(num);
            pageData.setCurrent((int) pages.getCurrent());
            pageData.setSize((int) pages.getSize());
            return pageData;
        } else {
            //大于10条 展示全部未处置完成火情
            List<CommFireAlarm> records = commFireAlarmDao.queryLeftFireInfo(districtCode);
            //2022-07-27只展示10条记录
            List<CommFireAlarm> commFireAlarms = this.setFireExtInfo(records.stream()
                    .limit(10)
                    .collect(Collectors.toList()));
            PageData<Object> pageData = new PageData<>();
            pageData.setDatas(commFireAlarms);
            pageData.setCount(num);
            pageData.setCurrent(1);
            pageData.setSize(commFireAlarms.size());
            return pageData;
        }
    }

    @Override
   // @Cacheable(value = "firecommand:fire:queryById",depict = "根据火情id查询火情基本信息(火情基本信息查询)")
    public CommFireAlarm queryById(Long fireId) {
        CommFireAlarm commFireAlarm = commFireAlarmDao.selectByPrimaryKey(fireId);
        if (commFireAlarm == null) {
            return null;
        }
        if (commFireAlarm.getHasDelete() != null && commFireAlarm.getHasDelete() == 1) {
            return null;
        } else {
            List<CommFireAlarm> commFireAlarms = new ArrayList<>(1);
            commFireAlarms.add(commFireAlarm);
            this.setExtInfo(commFireAlarms);
            return commFireAlarms.get(0);
        }
    }

    @Override
    public CommFireAlarm querySendFireById(Long fireId) {
        CommFireAlarm commFireAlarm = commFireAlarmDao.selectByPrimaryKey(fireId);
        if (commFireAlarm == null) {
            return null;
        }
        //已被删除的火情 不予推送
        if (commFireAlarm.getHasDelete() != null && commFireAlarm.getHasDelete() == 1) {
            return null;
        } else if (("3".equals(commFireAlarm.getResource()) || "8".equals(commFireAlarm.getResource()) || "9".equals(commFireAlarm.getResource()))
                && (ObjectUtil.isEmpty(commFireAlarm.getFireJudgmentType()) || (commFireAlarm.getFireJudgmentType() == 0 || commFireAlarm.getFireJudgmentType() == 3))) {
            //监控发现未判别 或 判别为误报的火情 不予推送
            return null;
        } else {
            List<CommFireAlarm> commFireAlarms = new ArrayList<>(1);
            commFireAlarms.add(commFireAlarm);
            this.setExtInfo(commFireAlarms);
            return commFireAlarms.get(0);
        }
    }

    @Override
    public List<CommFireAlarm> queryNotFinishFireByLongitudeAndLatitude(String longitude, String latitude,String districtCode) {
        List<CommFireAlarm> notFinishFire = commFireAlarmDao.queryNotFinishFire(null, districtCode);
        List<CommFireAlarm> fireAlarms = notFinishFire.stream().filter(e -> {
            double distanceMeter = GeoUtils.GetDistanceTwo(Double.parseDouble(longitude), Double.parseDouble(latitude), Double.parseDouble(e.getLongitude()), Double.parseDouble(e.getLatitude()));
            return distanceMeter < Double.parseDouble(limitDistance);
        }).collect(Collectors.toList());
        if (CollUtil.isNotEmpty(fireAlarms)) {
            this.setExtInfo(fireAlarms);
        }
        return fireAlarms;
    }


    /**
     * 火情设置扩展属性
     */
    private List<CommFireAlarm> setExtInfo(List<CommFireAlarm> list) {
        //2022-05-18 优化 避免过度请求 -------fixed by yzx-------start
        /*list.forEach(e -> {
            String code = e.getDistrictCode();
            e.setDistrictName(commFireAlarmDao.queryAddressNameByCode(code));
            String resource = e.getResource();
            Long deviceId = e.getDeviceId();
            switch (resource) {
                case "1":
                case "2":
                case "6":
                    //电话接警
                    //飞手
                    //护林员
                    e.setSourceName(e.getFinderName());
                    break;
                case "3":
                case "8":
                case "9":
                    //红外热成像
                    //可见光
                    //摄像头
                    if (deviceId != null) {
                        e.setSourceName(commCameraInfoDao.queryNameById(deviceId));
                    }
                    break;
                case "4":
                    //卫星
                    if (deviceId != null) {
                        e.setSourceName(commSatelliteInfoDao.queryNameById(deviceId));
                    }
                    break;
                case "5":
                    //无人机
                    if (deviceId != null) {
                        Object data = uavFeignClient.queryNameById(deviceId).getData();
                        if (data != null) {
                            e.setSourceName((String) data);
                        }
                    }
                    break;
                case "7":
                    //防火管理员
                    e.setSourceName(e.getFinderName());
                    if (deviceId != null) {
                        e.setDeviceName(commCameraInfoDao.queryNameById(deviceId));
                    }
                    break;
            }
            SysUserDetailVo sysUserVo;
            Long finderId = e.getFinderId();
            if (finderId != null) {
                sysUserVo = userInfoService.getUserInfo(finderId);
                if (sysUserVo != null) {
                    String username = sysUserVo.getRealName();
                    e.setFinderName(username);
                }
            }
            Long recieverId = e.getRecieverId();
            if (recieverId != null) {
                sysUserVo = userInfoService.getUserInfo(recieverId);
                if (sysUserVo != null) {
                    String username = sysUserVo.getRealName();
                    e.setRecieverName(username);
                }
            }
            Long confirmId = e.getConfirmId();
            if (confirmId != null) {
                sysUserVo = userInfoService.getUserInfo(confirmId);
                if (sysUserVo != null) {
                    String username = sysUserVo.getRealName();
                    e.setConfirmName(username);
                }
            }
            Long managementId = e.getManagementId();
            if (managementId != null) {
                sysUserVo = userInfoService.getUserInfo(managementId);
                if (sysUserVo != null) {
                    String username = sysUserVo.getRealName();
                    e.setManagementName(username);
                }
            }
            Long finishId = e.getFinishId();
            if (finishId != null) {
                sysUserVo = userInfoService.getUserInfo(finishId);
                if (sysUserVo != null) {
                    String username = sysUserVo.getRealName();
                    e.setFinishName(username);
                }
            }
            String imageUrl = e.getImageUrl();
            List<String> mediaUrlList = MediaUrlUtils.handleMediaUrlToList(imageUrl);
            e.setMediaUrlList(mediaUrlList);
            FireReportSuperiorLog fireReportSuperiorLog = fireReportSuperiorLogDao.queryByFireId(e.getId(), 0);
            if (fireReportSuperiorLog != null) {
                e.setReportName(fireReportSuperiorLog.getReportPersonName());
            }
        });*/
        final List<Long> ids = CollUtil.newArrayList();
        list.forEach(e -> {
            ids.add(e.getFinderId());
            ids.add(e.getRecieverId());
            ids.add(e.getConfirmId());
            ids.add(e.getManagementId());
            ids.add(e.getFinishId());
        });
        final Map<Long, String> idNameMapping = userInfoService.findAndConvertUserInfoByIds(ids);
        List<String> districtCodeList=new ArrayList<>();
        list.forEach(e -> {
            String code = e.getDistrictCode();
            if (StrUtil.isNotEmpty(code)) {
                districtCodeList.add(code);
            }
//            e.setDistrictName(commFireAlarmDao.queryAddressNameByCode(code));
            String resource = e.getResource();
            Long deviceId = e.getDeviceId();
            switch (resource) {
                case "1":
                case "2":
                case "6":
                    //电话接警
                    //飞手
                    //护林员
                    e.setSourceName(e.getFinderName());
                    break;
                case "3":
                case "8":
                case "9":
                    //红外热成像
                    //可见光
                    //摄像头
//                    if (deviceId != null) {
//                        e.setSourceName(commCameraInfoDao.queryNameById(deviceId));
//                    }
                    e.setSourceName(e.getFinderName());
                    break;
                case "4":
                    //卫星
                    if (deviceId != null) {
                        CommSatelliteInfo commSatelliteInfo = commSatelliteInfoDao.selectByPrimaryKey(deviceId);
                        if (commSatelliteInfo != null) {
                            e.setSourceName(commSatelliteInfo.getName());
                        }
                    }
                    break;
                case "5":
                    //无人机
//                    if (deviceId != null) {
//                        Object data = uavFeignClient.queryNameById(deviceId).getData();
//                        if (data != null) {
//                            e.setSourceName((String) data);
//                        }
//                    }
                    break;
                case "7":
                    //防火管理员
                    e.setSourceName(e.getFinderName());
//                    if (deviceId != null) {
//                        e.setDeviceName(commCameraInfoDao.queryNameById(deviceId));
//                    }
                    break;
            }
            //优化后的写法
            e.setFinderName(StrUtil.isEmpty(e.getFinderName()) ? ObjectUtil.defaultIfNull(idNameMapping.get(e.getFinderId()), StrUtil.EMPTY) : e.getFinderName());
            e.setRecieverName(StrUtil.isEmpty(e.getRecieverName()) ? ObjectUtil.defaultIfNull(idNameMapping.get(e.getRecieverId()), StrUtil.EMPTY) : e.getRecieverName());
            e.setConfirmName(StrUtil.isEmpty(e.getConfirmName()) ? ObjectUtil.defaultIfNull(idNameMapping.get(e.getConfirmId()), StrUtil.EMPTY) : e.getConfirmName());
            e.setManagementName(StrUtil.isEmpty(e.getManagementName()) ? ObjectUtil.defaultIfNull(idNameMapping.get(e.getManagementId()), StrUtil.EMPTY) : e.getManagementName());
            e.setFinishName(StrUtil.isEmpty(e.getFinishName()) ? ObjectUtil.defaultIfNull(idNameMapping.get(e.getFinishId()), StrUtil.EMPTY) : e.getFinishName());
            String imageUrl = e.getImageUrl();
            List<String> mediaUrlList = MediaUrlUtils.handleMediaUrlToList(imageUrl);
            e.setMediaUrlList(mediaUrlList);
            FireReportSuperiorLog fireReportSuperiorLog = fireReportSuperiorLogDao.queryByFireId(e.getId(), 0);
            if (fireReportSuperiorLog != null) {
                e.setReportName(fireReportSuperiorLog.getReportPersonName());
            }
        });
        //2022-05-18 优化 避免过度请求 -------fixed by yzx-------end
        //创建行政区划和名称的map集合
        final List<Map<String,String>> addressMappingList=commFireAlarmDao.queryAddressNamesByCodeList(districtCodeList);
        final Map<String,String> addressMapping=new HashMap<>();
        addressMappingList.forEach(e->{
            addressMapping.put(e.get("districtcode"),e.get("address"));
        });
        list.forEach(e->{
            e.setDistrictName(addressMapping.get(e.getDistrictCode()));
        });
//        for (CommFireAlarm commFireAlarm:list){
//            commFireAlarm.setDistrictName(addressMapping.get(commFireAlarm.getDistrictCode()));
//        }
        return list;
    }

    /**
     * 电话接警火情设置扩展属性
     */
    private List<CommFireAlarm> setTelephoneAlarmExtInfo(List<CommFireAlarm> list) {
        final List<Long> ids = CollUtil.newArrayList();
        list.forEach(e -> {
            ids.add(e.getFinderId());
        });
        final Map<Long, String> idNameMapping = userInfoService.findAndConvertUserInfoByIds(ids);
        List<String> districtCodeList=new ArrayList<>();
        list.forEach(e -> {
            String code = e.getDistrictCode();
            if (StrUtil.isNotEmpty(code)) {
                districtCodeList.add(code);
            }
            //电话接警
            e.setSourceName(e.getFinderName());
            e.setFinderName(StrUtil.isEmpty(e.getFinderName()) ? ObjectUtil.defaultIfNull(idNameMapping.get(e.getFinderId()), StrUtil.EMPTY) : e.getFinderName());
        });
        //创建行政区划和名称的map集合
        final List<Map<String,String>> addressMappingList=commFireAlarmDao.queryAddressNamesByCodeList(districtCodeList);
        final Map<String,String> addressMapping=new HashMap<>();
        addressMappingList.forEach(e->{
            addressMapping.put(e.get("districtcode"),e.get("address"));
        });
        list.forEach(e->{
            e.setDistrictName(addressMapping.get(e.getDistrictCode()));
        });
        return list;
    }

    /**
     * 火情设置扩展属性
     */
    private List<CommFireAlarm> setFireExtInfo(List<CommFireAlarm> list) {
        final List<Long> ids = CollUtil.newArrayList();
        //设备id集合
        List<Long> deviceIdList = new ArrayList<>();
        //来源集合
        List<String> resourceList = new ArrayList<>();
        list.forEach(e -> {
            ids.add(e.getFinderId());
            ids.add(e.getRecieverId());
            ids.add(e.getConfirmId());
            ids.add(e.getManagementId());
            ids.add(e.getFinishId());
            if(e.getDeviceId() != null){
                deviceIdList.add(e.getDeviceId());
            }
            if(e.getResource() != null){
                resourceList.add(e.getResource());
            }
        });
        final Map<Long, String> idNameMapping = userInfoService.findAndConvertUserInfoByIds(ids);
        List<String> districtCodeList = new ArrayList<>();
        //监控集合
        Map<Long, String> cameraMapping = new HashMap<>();
//        if(resourceList.contains("3") || resourceList.contains("8") || resourceList.contains("9")){
//            List<Map<String,String>> cameraDeviceIds = commCameraInfoDao.queryNameByIds(deviceIdList) ;
//            cameraDeviceIds.forEach(e -> {
//                cameraMapping.put(Convert.toLong(e.get("id")),e.get("name"));
//            });
//        }
        //卫星集合
        Map<Long, String> satelliteMapping = new HashMap<>();
        if (resourceList.contains("4")) {
            List<CommSatelliteInfo> commSatelliteInfos = commSatelliteInfoDao.selectAll();
            satelliteMapping = commSatelliteInfos.stream().collect(
                    Collectors.toMap(CommSatelliteInfo::getId, CommSatelliteInfo::getName, (e1, e2) -> e1));
        }
        //无人机集合
        Map<Long, String> uavMapping = new HashMap<>();
//        if(resourceList.contains("5")){
//            List<Map<String,String>> uavIds = (List<Map<String,String>>)uavFeignClient.queryNameByIds(deviceIdList).getData();
//            uavIds.forEach(e -> {
//                uavMapping.put(Convert.toLong(e.get("id")),e.get("uav_code"));
//            });
//        }
        Map<Long, String> finalSatelliteMapping = satelliteMapping;
        list.forEach(e -> {
            String code = e.getDistrictCode();
            if (StrUtil.isNotEmpty(code)) {
                districtCodeList.add(code);
            }
            String resource = e.getResource();
            switch (resource) {
                case "1":
                case "2":
                case "6":
                    //电话接警
                    //飞手
                    //护林员
                    e.setSourceName(e.getFinderName());
                    break;
                case "3":
                case "8":
                case "9":
                    //红外热成像
                    //可见光
                    //摄像头
                    if (CollUtil.isNotEmpty(cameraMapping)) {
                        e.setSourceName(cameraMapping.get(e.getDeviceId()));
                    }
                    break;
                case "4":
                    //卫星
                    if (CollUtil.isNotEmpty(finalSatelliteMapping)) {
                        e.setSourceName(finalSatelliteMapping.get(e.getDeviceId()));
                    }
                    break;
                case "5":
                    //无人机
                    if (CollUtil.isNotEmpty(uavMapping)) {
                        e.setSourceName(uavMapping.get(e.getDeviceId()));
                    }
                    break;
                case "7":
                    //防火管理员
                    e.setSourceName(e.getFinderName());
                    if (CollUtil.isNotEmpty(cameraMapping)) {
                        e.setDeviceName(cameraMapping.get(e.getDeviceId()));
                    }
                    break;
            }
            //优化后的写法
            e.setFinderName(StrUtil.isEmpty(e.getFinderName()) ? ObjectUtil.defaultIfNull(idNameMapping.get(e.getFinderId()), StrUtil.EMPTY) : e.getFinderName());
            e.setRecieverName(StrUtil.isEmpty(e.getRecieverName()) ? ObjectUtil.defaultIfNull(idNameMapping.get(e.getRecieverId()), StrUtil.EMPTY) : e.getRecieverName());
            e.setConfirmName(StrUtil.isEmpty(e.getConfirmName()) ? ObjectUtil.defaultIfNull(idNameMapping.get(e.getConfirmId()), StrUtil.EMPTY) : e.getConfirmName());
            e.setManagementName(StrUtil.isEmpty(e.getManagementName()) ? ObjectUtil.defaultIfNull(idNameMapping.get(e.getManagementId()), StrUtil.EMPTY) : e.getManagementName());
            e.setFinishName(StrUtil.isEmpty(e.getFinishName()) ? ObjectUtil.defaultIfNull(idNameMapping.get(e.getFinishId()), StrUtil.EMPTY) : e.getFinishName());
            String imageUrl = e.getImageUrl();
            List<String> mediaUrlList = MediaUrlUtils.handleMediaUrlToList(imageUrl);
            e.setMediaUrlList(mediaUrlList);
            FireReportSuperiorLog fireReportSuperiorLog = fireReportSuperiorLogDao.queryByFireId(e.getId(), 0);
            if (fireReportSuperiorLog != null) {
                e.setReportName(fireReportSuperiorLog.getReportPersonName());
            }
        });
        //2022-05-18 优化 避免过度请求 -------fixed by yzx-------end
        //创建行政区划和名称的map集合
        final List<Map<String,String>> addressMappingList=commFireAlarmDao.queryAddressNamesByCodeList(districtCodeList);
        final Map<String,String> addressMapping=new HashMap<>();
        addressMappingList.forEach(e->{
            addressMapping.put(e.get("districtcode"),e.get("address"));
        });
        list.forEach(e->{
            e.setDistrictName(addressMapping.get(e.getDistrictCode()));
        });
        return list;
    }

    @Override
    public HistoryFireCountDTO queryCountHistoryFireByYear(String year, String districtCode, String startTime,
                                                           String endTime, String fireLevel, String resource) {
        Integer countNum = commFireAlarmDao.queryCountByYear(year, districtCode, startTime, endTime, fireLevel,
                resource);

        //火情等级统计
        HistoryFireCountDTO historyFireCountDTO = new HistoryFireCountDTO();
        List<Map<String, Object>> data2 = commFireAlarmDao.queryCountByYearAndLevel(year, districtCode, startTime,
                endTime, fireLevel, resource);
        List<ForestFireCountDTO> forestFireCountDTOS = new ArrayList<>(data2.size());
        data2.forEach(e -> {
            String name = (String) e.get("name");
            Long count = (Long) e.get("count");
            ForestFireCountDTO forestFireCountDTO = new ForestFireCountDTO();
            forestFireCountDTO.setNumber(count);
            forestFireCountDTO.setLevel(name);
            forestFireCountDTO.setPercent(BigDecimal.ZERO);
            if (count != 0) {
                forestFireCountDTO.setPercent(
                        new BigDecimal(count).divide(new BigDecimal(countNum), 4, BigDecimal.ROUND_HALF_UP));
            }
            forestFireCountDTOS.add(forestFireCountDTO);
        });
        historyFireCountDTO.setForestFireCountDTOS(forestFireCountDTOS);

        //火情来源
        List<WarnFireCountDTO> warnFireCountDTOS = new ArrayList<>();
        List<Map<String, Object>> resourceList = commFireAlarmDao.queryCountByYearAndResource(year, districtCode,
                startTime, endTime, fireLevel, resource);
        Map<String, WarnFireCountDTO> resource2Count = new HashMap<>();
        resourceList.forEach(map -> {
            String source = MapUtil.getStr(map, "resource");
            Long count = MapUtil.getLong(map, "count");
            WarnFireCountDTO warnFireCountDTO = WarnFireCountDTO.builder()
                    .source(source)
                    .number(count)
                    .build();
            if (count != 0) {
                warnFireCountDTO.setPercent(
                        new BigDecimal(count).divide(new BigDecimal(countNum), 4, BigDecimal.ROUND_HALF_UP));
            }
            resource2Count.put(source, warnFireCountDTO);
        });

        Map<String, WarnFireCountDTO> resourceMap = new HashMap<>();
        List<DictVO> dictVOList = dictMapper.listByParentCode("fire_resource_type");
        Map<String, String> dictMap = dictVOList.stream().collect(
                Collectors.toMap(DictVO::getCode, DictVO::getName, (e1, e2) -> e1));
        dictMap.keySet().forEach(key -> {
            resourceMap.put(dictMap.get(key), resource2Count.get(key));
            WarnFireCountDTO warnFireCountDTO = resource2Count.get(key);
            if (warnFireCountDTO == null) {
                warnFireCountDTO = WarnFireCountDTO.builder()
                        .source(dictMap.get(key))
                        .number((long) 0)
                        .percent(BigDecimal.ZERO)
                        .build();
            } else {
                warnFireCountDTO.setSource(dictMap.get(key));
            }
            warnFireCountDTOS.add(warnFireCountDTO);
        });
        historyFireCountDTO.setWarnFireCountDTOS(warnFireCountDTOS);

        //行政区划统计
        if (StrUtil.isNotEmpty(districtCode) && districtCode.length() == 9) {
            List<Map<String, Object>> data3 = commFireAlarmDao.queryFireCountByDistrictCode(year, districtCode,
                    startTime, endTime, fireLevel, resource, "5");
//                List<DistrictFireCountDTO> districtFireCountDTOS = new ArrayList<>(data3.size());
            List<String> list = geoXzqhCunDao.queryAllCunByDistrictCode(districtCode);
            List<DistrictFireCountDTO> districtFireCountDTOS = new ArrayList<>();
//                Set<String> set = new HashSet<>(list.size());
//                set.addAll(list);
            for (String e : list) {
                DistrictFireCountDTO districtFireCountDTO = new DistrictFireCountDTO();
                districtFireCountDTO.setCun(e);
                districtFireCountDTO.setNumber(0L);
                districtFireCountDTO.setPercent(new BigDecimal(0));
                districtFireCountDTOS.add(districtFireCountDTO);
            }
            data3.forEach(e -> {
                String district = MapUtil.getStr(e, "district");
                int index = list.indexOf(district);
                Long count = MapUtil.getLong(e, "count");

                DistrictFireCountDTO districtFireCountDTO = new DistrictFireCountDTO();
                districtFireCountDTO.setCun(district);
                districtFireCountDTO.setNumber(count);
                if (count != 0) {
                    districtFireCountDTO.setPercent(
                            new BigDecimal(count).divide(new BigDecimal(countNum), 4, BigDecimal.ROUND_HALF_UP));
                }
                districtFireCountDTOS.set(index, districtFireCountDTO);
            });

            historyFireCountDTO.setDistrictFireCountDTOS(districtFireCountDTOS);
            return historyFireCountDTO;
        } else if (StrUtil.isNotEmpty(districtCode) && districtCode.length() == 6) {
            List<Map<String, Object>> data3 = commFireAlarmDao.queryFireCountByDistrictCode1(year, districtCode,
                    startTime, endTime, fireLevel, resource, "5");
//                List<DistrictFireCountDTO> districtFireCountDTOS = new ArrayList<>(data3.size());
            List<String> list = geoXzqhCunDao.queryAllXiangByDistrictCode(districtCode);
            List<DistrictFireCountDTO> districtFireCountDTOS = new ArrayList<>();
//                Set<String> set = new HashSet<>(list.size());
//                set.addAll(list);
            for (String e : list) {
                DistrictFireCountDTO districtFireCountDTO = new DistrictFireCountDTO();
                districtFireCountDTO.setCun(e);
                districtFireCountDTO.setNumber(0L);
                districtFireCountDTO.setPercent(new BigDecimal(0));
                districtFireCountDTOS.add(districtFireCountDTO);
            }
            data3.forEach(e -> {
                String district = MapUtil.getStr(e, "district");
                int index = list.indexOf(district);
                Long count = MapUtil.getLong(e, "count");
                DistrictFireCountDTO districtFireCountDTO = new DistrictFireCountDTO();
                districtFireCountDTO.setCun(district);
                districtFireCountDTO.setNumber(count);
                if (count != 0) {
                    districtFireCountDTO.setPercent(
                            new BigDecimal(count).divide(new BigDecimal(countNum), 4, BigDecimal.ROUND_HALF_UP));
                }
                districtFireCountDTOS.set(index, districtFireCountDTO);
            });

            historyFireCountDTO.setDistrictFireCountDTOS(districtFireCountDTOS);
            return historyFireCountDTO;
        } else if (StrUtil.isNotEmpty(districtCode) && districtCode.length() == 4) {
            List<Map<String, Object>> data3 = commFireAlarmDao.queryFireCountByDistrictCode2(year, districtCode,
                    startTime, endTime, fireLevel, resource, "5");
//                List<DistrictFireCountDTO> districtFireCountDTOS = new ArrayList<>(data3.size());
            List<String> list = geoXzqhCunDao.queryAllXianByDistrictCode(districtCode);
            List<DistrictFireCountDTO> districtFireCountDTOS = new ArrayList<>();
//                Set<String> set = new HashSet<>(list.size());
//                set.addAll(list);
            for (String e : list) {
                DistrictFireCountDTO districtFireCountDTO = new DistrictFireCountDTO();
                districtFireCountDTO.setCun(e);
                districtFireCountDTO.setNumber(0L);
                districtFireCountDTO.setPercent(new BigDecimal(0));
                districtFireCountDTOS.add(districtFireCountDTO);
            }
            data3.forEach(e -> {
                String district = MapUtil.getStr(e, "district");
                int index = list.indexOf(district);
                Long count = MapUtil.getLong(e, "count");
                DistrictFireCountDTO districtFireCountDTO = new DistrictFireCountDTO();
                districtFireCountDTO.setCun(district);
                districtFireCountDTO.setNumber(count);
                if (count != 0) {
                    districtFireCountDTO.setPercent(
                            new BigDecimal(count).divide(new BigDecimal(countNum), 4, BigDecimal.ROUND_HALF_UP));
                }
                districtFireCountDTOS.set(index, districtFireCountDTO);
            });

            historyFireCountDTO.setDistrictFireCountDTOS(districtFireCountDTOS);
            return historyFireCountDTO;
        } else {
            List<Map<String, Object>> data3 = commFireAlarmDao.queryDistrictFireCount(year, districtCode, startTime,
                    endTime, fireLevel, resource, "5");
            List<DistrictFireCountDTO> districtFireCountDTOS = new ArrayList<>(data3.size());
            List<String> list = geoXzqhXiangDao.queryAllXiang();
//                Set<String> set = new HashSet<>(list.size());
//                set.addAll(list);
            list.forEach(e -> {
                DistrictFireCountDTO districtFireCountDTO = new DistrictFireCountDTO();
                districtFireCountDTO.setCun(e);
                districtFireCountDTO.setNumber(0L);
                districtFireCountDTO.setPercent(new BigDecimal(0));
                districtFireCountDTOS.add(districtFireCountDTO);
            });
            data3.forEach(e -> {
                String district = MapUtil.getStr(e, "district");
                int index = list.indexOf(district);
                Long count = MapUtil.getLong(e, "count");
                DistrictFireCountDTO districtFireCountDTO = new DistrictFireCountDTO();
                districtFireCountDTO.setCun(district);
                districtFireCountDTO.setNumber(count);
                if (count != 0) {
                    districtFireCountDTO.setPercent(
                            new BigDecimal(count).divide(new BigDecimal(countNum), 4, BigDecimal.ROUND_HALF_UP));
                }
                districtFireCountDTOS.set(index, districtFireCountDTO);
            });

            //2022-06-08 查询出的结果带街道排序
            final List<CommCountrysideSort> dbCountrySort = ChainWrappers.lambdaQueryChain(commCountrysideSortDao)
                    .orderByAsc(CommCountrysideSort::getSort)
                    .list();
            if (CollUtil.isEmpty(dbCountrySort)) {
                historyFireCountDTO.setDistrictFireCountDTOS(districtFireCountDTOS);
                return historyFireCountDTO;
            }

            final Map<String, DistrictFireCountDTO> convertMap = districtFireCountDTOS.stream().collect(
                    Collectors.toMap(DistrictFireCountDTO::getCun, e -> e));
            final List<DistrictFireCountDTO> res = dbCountrySort.stream()
                    .map(e -> {
                        final DistrictFireCountDTO dto = new DistrictFireCountDTO();
                        dto.setCun(e.getCountrysideName());
                        //获得原加工后的数据
                        final DistrictFireCountDTO temp = convertMap.get(e.getCountrysideName());
                        if (ObjectUtil.isEmpty(temp)) {
                            dto.setNumber(BigDecimal.ZERO.longValue());
                            dto.setPercent(BigDecimal.ZERO);
                        } else {
                            dto.setNumber(temp.getNumber());
                            dto.setPercent(temp.getPercent());
                        }
                        return dto;
                    }).collect(Collectors.toList());
            log.info("街道排序后:[{}]", JSONUtil.toJsonPrettyStr(res));
            historyFireCountDTO.setDistrictFireCountDTOS(res);
        }

        return historyFireCountDTO;
    }

    @Override
    public HistoryFireDTO queryHisFireDetailById(Long fireId) {
        CommFireAlarm commFireAlarm = commFireAlarmDao.selectByPrimaryKey(fireId);
        List<CommFireAlarm> list = new ArrayList<>(1);
        list.add(commFireAlarm);
        this.setExtInfo(list);
        CommHistoryFire commHistoryFire = commHistoryFireDao.queryByFireId(fireId);
        CommFireHandle commFireHandle = fireHandleDao.queryByFireId(fireId);
        HistoryFireDTO historyFireDTO = new HistoryFireDTO();
        historyFireDTO.setCommFireAlarm(list.get(0));
        historyFireDTO.setCommHistoryFire(commHistoryFire);
        historyFireDTO.setCommFireHandle(commFireHandle);
        return historyFireDTO;
    }

    @Override
    public Map<String, List<MultimediaDTO>> queryMediaById(Long fireId) {
        Map<String, List<MultimediaDTO>> resultMap = new HashMap<>();
        List<MultimediaDTO> imgList = new ArrayList<>();
        List<MultimediaDTO> audioList = new ArrayList<>();
        List<MultimediaDTO> videoList = new ArrayList<>();
        List<MultimediaDTO> docList = new ArrayList<>();
        // 查询火情表的多媒体信息
        CommFireAlarm commFireAlarm = commFireAlarmDao.queryMedia(fireId);
        DictVO dictVO = dictMapper.findDictInfoByCode(DictTypeConstants.DICT_TYPE_FIRE_ALARM_RESOURCE,
                commFireAlarm.getResource());
        if (StringUtils.isNoneBlank(commFireAlarm.getImageUrl())) {
            List<String> fireImgList = JSON.parseArray(commFireAlarm.getImageUrl(), String.class);
            if (!CollectionUtils.isEmpty(fireImgList)) {
                fireImgList.forEach(fireImg -> {
                    // 封装数据
                    MultimediaDTO multimediaDTO = new MultimediaDTO(fireImg, dictVO == null ? null : dictVO.getName(),
                            commFireAlarm.getFindTime(), commFireAlarm.getFinderName());
                    multimediaDTO.setMediaUrl(fireImg);
                    // 判断是哪个list里面的数据
                    String fileType = fireImg.substring(fireImg.indexOf(".") + 1);
                    classification(fileType, multimediaDTO, imgList, videoList, audioList, docList);
                });
            }
        }

        // 查询上传图片记录表中多媒体信息
        List<FileUploadLog> fileUploadLogList = fileUploadLogDao.listByFireId(fireId);
        if (!CollectionUtils.isEmpty(fileUploadLogList)) {
            fileUploadLogList.forEach(fileUploadLog -> {
                if (fileUploadLog != null && StringUtils.isNotBlank(fileUploadLog.getFilePath())) {
                    String filePath = fileUploadLog.getFilePath();
                    DictVO dVo = dictMapper.findDictInfoByCode(DictTypeConstants.DICT_TYPE_FIRE_ALARM_RESOURCE,
                            fileUploadLog.getAlarmResource());
                    // 封装数据
                    MultimediaDTO multimediaDTO = new MultimediaDTO(fileUploadLog.getFilePath(),
                            dVo == null ? null : dVo.getName(), fileUploadLog.getUploadTime(),
                            fileUploadLog.getUploader());
                    String fileType = filePath.substring(filePath.indexOf(".") + 1);
                    classification(fileType, multimediaDTO, imgList, videoList, audioList, docList);
                }
            });
        }
        resultMap.put("audioList", audioList);
        resultMap.put("imgList", imgList);
        resultMap.put("videoList", videoList);
        resultMap.put("docList", docList);
        return resultMap;
    }

    /**
     * 只查询火情上报时候的多媒体信息
     *
     * @param fireId 火情id
     *
     * @return Map<String, List < MultimediaDTO>>
     */
    @Override
    public Map<String, List<MultimediaDTO>> queryOnlyAddMediaById(Long fireId) {
        List<MultimediaDTO> imgList = new ArrayList<>();
        List<MultimediaDTO> audioList = new ArrayList<>();
        List<MultimediaDTO> videoList = new ArrayList<>();
        List<MultimediaDTO> docList = new ArrayList<>();
        // 查询火情表的多媒体信息
        CommFireAlarm commFireAlarm = commFireAlarmDao.queryMedia(fireId);
        DictVO dictVO = dictMapper.findDictInfoByCode(DictTypeConstants.DICT_TYPE_FIRE_ALARM_RESOURCE,
                commFireAlarm.getResource());
        if (StringUtils.isNoneBlank(commFireAlarm.getImageUrl())) {
            List<String> fireImgList = JSON.parseArray(commFireAlarm.getImageUrl(), String.class);
            if (!CollectionUtils.isEmpty(fireImgList)) {
                fireImgList.forEach(fireImg -> {
                    // 封装数据
                    MultimediaDTO multimediaDTO = new MultimediaDTO(fireImg, dictVO == null ? null : dictVO.getName(),
                            commFireAlarm.getFindTime(), commFireAlarm.getFinderName());
                    multimediaDTO.setMediaUrl(fireImg);
                    // 判断是哪个list里面的数据
                    String fileType = fireImg.substring(fireImg.indexOf(".") + 1);
                    classification(fileType, multimediaDTO, imgList, videoList, audioList, docList);
                });
            }
        }

        Map<String, List<MultimediaDTO>> resultMap = new HashMap<>();
        resultMap.put("audioList", audioList);
        resultMap.put("imgList", imgList);
        resultMap.put("videoList", videoList);
        resultMap.put("docList", docList);
        return resultMap;
    }

    @Override
    public CommCameraInfo queryCameraByFireId(Long fireId) {
        List<CommCameraInfo> commCameraInfos = commFireAlarmDao.queryCameraByFireId(fireId);
        if (commCameraInfos != null && commCameraInfos.size() > 0) {
            // CameraInfoUtil.setDistrictName(commCameraInfos, geoXzqhCunDao);
            return commCameraInfos.get(0);
        } else {
            return null;
        }
    }

    @Override
    public EmergencyDrillDetailDTO queryEmergencyPlanDetailById(Long fireId) {
        EmergencyDrillDetailDTO emergencyDrillDetailDTO = new EmergencyDrillDetailDTO();
        CommFireAlarm commFireAlarm = commFireAlarmDao.selectByPrimaryKey(fireId);
        emergencyDrillDetailDTO.setCommFireAlarm(commFireAlarm);
//        EmergencyDrillInfo emergencyPlanInfo = emergencyDrillInfoDao.selectByPrimaryKey(fireId);
//        emergencyDrillDetailDTO.setEmergencyDrillInfo(emergencyPlanInfo);
        return emergencyDrillDetailDTO;
    }

    public void classification(String fileType, MultimediaDTO multimediaDTO, List<MultimediaDTO> imgList,
                               List<MultimediaDTO> videoList, List<MultimediaDTO> audioList,
                               List<MultimediaDTO> docList) {
        if (FILE_TYPE_IMAGE_LIST.contains(fileType)) {
            imgList.add(multimediaDTO);
        } else if (FILE_TYPE_VIDEO_LIST.contains(fileType)) {
            videoList.add(multimediaDTO);
        } else if (FILE_TYPE_AUDIO_LIST.contains(fileType)) {
            audioList.add(multimediaDTO);
        } else {
            docList.add(multimediaDTO);
        }
    }

    @Override
    public List<Map<Object, Object>> queryAllSource() {
        //2022-04-18 临时处理，将无人机去掉，不从数据库做reason 避免影响到其他业务
        return commFireAlarmDao.queryAllSource()/*.stream()
                .filter(m -> !StrUtil.equals(Convert.toStr(m.get("name")),"无人机"))
                .collect(Collectors.toList())*/;
    }

    @Override
    public List<CommFireAlarm> queryIncompleteDisposalFire(Long fireId, String  districtCode) {
        //获取当前用户区级或者街道级行政区划代码
        //app端调用传villageDistrictCode参数，防止修改权限APP需重新登录问题
        List<CommFireAlarm> notFinishFire = commFireAlarmDao.queryNotFinishFire(fireId,  districtCode);
        List<CommFireAlarm> commFireAlarms = this.setFireExtInfo(notFinishFire);
        return commFireAlarms;
    }

    @Override
    public List<CommFireAlarm> queryIncompleteDisposalFireByPoint(String firePoint) {
        List<CommFireAlarm> notFinishFire = commFireAlarmDao.queryNotFinishFireByPoint(firePoint);
        List<CommFireAlarm> commFireAlarms = this.setExtInfo(notFinishFire);
        return commFireAlarms;
    }

    @Override
    public PageData<Object> queryAllSampleLibrary(String startTime, String endTime, String districtCode, Integer judgement, int page, int rows) {
        IPage<SampleLibraryDto> iPage = new Page<>(page, rows);
        //人工值守平台样本库数据获取
        IPage<SampleLibraryDto> pages = commFireAlarmDao.queryAllSampleLibrary(iPage, startTime, endTime, districtCode, judgement);
        List<SampleLibraryDto> sampleLibraryDtoList = pages.getRecords();
        //返回数据不为null
        if (sampleLibraryDtoList != null && sampleLibraryDtoList.size() > 0) {
            //创建行政区划代码集合
            List<String> districtCodeList=new ArrayList<>();
            sampleLibraryDtoList.stream().forEach(sampleLibraryDto -> {
                List<String> fullImageUrlList = new ArrayList<>();
                String imageUrl = sampleLibraryDto.getImageUrl();
                if (StringUtils.isNotEmpty(imageUrl)) {
                    //转换图片字符串为集合
                    List<String> imageUrlList = JSON.parseArray(imageUrl, String.class);
                    imageUrlList.stream().forEach(subImageUrl -> {
                        //获取到每张图片完整路径名称
                        String fullImageUrl = MinioUtils.previewImg(subImageUrl);
                        //放入到集合中
                        fullImageUrlList.add(fullImageUrl);
                    });
                }
                //设置到实体中
                sampleLibraryDto.setImageUrl(fullImageUrlList.toString());
                //把行政区划代码存入集合
                if(StrUtil.isNotEmpty(sampleLibraryDto.getDistrictCode())){
                    districtCodeList.add(sampleLibraryDto.getDistrictCode());
                }
            });

            //根据行政区划集合查询行政区划名称
//            if(!CollectionUtils.isEmpty(districtCodeList)) {
//                Result<Map<String, String>> districtCodeNameMapResult = upmsFeignClient.queryDistrictNameByCodes(districtCodeList);
//                if(ObjectUtil.isNotEmpty(districtCodeNameMapResult.getData())){
//                    //获取行政区划代码和行政区划名称的map
//                    Map<String, String> districtCodeNameMap = districtCodeNameMapResult.getData();
//                    if (sampleLibraryDtoList != null && sampleLibraryDtoList.size() > 0) {
//                        sampleLibraryDtoList.stream().forEach(sampleLibraryDto ->{
//                            //设置行政区划名称
//                            if(StrUtil.isNotEmpty(sampleLibraryDto.getDistrictCode())) {
//                                sampleLibraryDto.setDistrictName(districtCodeNameMap.get(sampleLibraryDto.getDistrictCode()).replace("/",""));
//                            }
//                        });
//                    }
//                }
//            }
        }
        PageData<Object> pageData = new PageData<>();
        pageData.setDatas(sampleLibraryDtoList);
        pageData.setCount((int) pages.getTotal());
        pageData.setCurrent((int) pages.getCurrent());
        pageData.setSize((int) pages.getSize());
        return pageData;
    }

    @Override
    //@Cacheable(value = "firecommand:fire:queryUnfinishedFireByDay",depict = "通过时间区间查询未处置完成的火情")
    public List<LonAndLatDTO> queryUnfinishedFireByDay(String day, String districtCode) {
        return commFireAlarmDao.queryUnfinishedFireByDay(day, districtCode);
    }

    @Override
    public List<CommFireAlarm> queryListByFireIds(List<Long> fireIdList) {
        return commFireAlarmDao.queryListByFireIds(fireIdList);
    }


    @Override
    public Object queryAllHistoryFire(String startTime, String endTime, String districtCode, String fireLevel,
                                      String resource, Integer page, Integer rows) {

        if (page != null && rows != null) {
            IPage<CommFireAlarm> appTaskStatusPage = new Page<>(page, rows);
            IPage<CommFireAlarm> pages = commFireAlarmDao.queryAllHistoryFire(appTaskStatusPage, startTime, endTime,
                    districtCode, fireLevel, resource);
            List<CommFireAlarm> records = pages.getRecords();
            List<CommFireAlarm> commFireAlarms = this.setExtInfo(records);
            pages.setRecords(commFireAlarms);
            PageData<Object> pageData = new PageData<>();
            pageData.setDatas(pages.getRecords());
            pageData.setCount((int) pages.getTotal());
            pageData.setCurrent((int) pages.getCurrent());
            pageData.setSize((int) pages.getSize());
            return pageData;
        } else {
            List<CommFireAlarm> commFireAlarms = commFireAlarmDao.queryAllHistoryFireNoPage(startTime, endTime,
                    districtCode, fireLevel, resource);
            List<CommFireAlarm> commFireAlarm = this.setExtInfo(commFireAlarms);
            Map<String, Object> map = new HashMap<>(2);
            map.put("data", commFireAlarm);
            map.put("total", commFireAlarm.size());
            return map;
        }
    }

    @Override
    public SimpleFireAlarmDTO queryAddress(Long fireId) {
        CommFireAlarm commFireAlarm = commFireAlarmDao.selectByPrimaryKey(fireId);
        SimpleFireAlarmDTO dto = new SimpleFireAlarmDTO();
        if (commFireAlarm != null) {
            BeanUtils.copyProperties(commFireAlarm, dto);
            dto.setDistrictName(commFireAlarmDao.queryAddressNameByCode(dto.getDistrictCode()));
        }
        return dto;
    }

    @Override
    public Object queryAllHistoryEmergencyFire(String startTime, String endTime, String districtCode, Integer page, Integer rows) {
        if (StringUtils.isNotBlank(districtCode)) {
            districtCode = districtCode + "%";
        }
        if (page != null && rows != null) {
            IPage<CommFireAlarm> appTaskStatusPage = new Page<>(page, rows);
            IPage<CommFireAlarm> pages = commFireAlarmDao.queryAllHistoryEmergencyFire(appTaskStatusPage, startTime, endTime, districtCode);
            List<CommFireAlarm> records = pages.getRecords();
            List<CommFireAlarm> commFireAlarms = this.setExtInfo(records);
            pages.setRecords(commFireAlarms);
            PageData<Object> pageData = new PageData<>();
            pageData.setDatas(pages.getRecords());
            pageData.setCount((int) pages.getTotal());
            pageData.setCurrent((int) pages.getCurrent());
            pageData.setSize((int) pages.getSize());
            return pageData;
        } else {
            List<CommFireAlarm> commFireAlarms = commFireAlarmDao.queryAllHistoryEmergencyFireNoPage(startTime, endTime, districtCode);
            List<CommFireAlarm> commFireAlarm = this.setExtInfo(commFireAlarms);
            Map<String, Object> map = new HashMap<>(2);
            map.put("data", commFireAlarm);
            map.put("total", commFireAlarm.size());
            return map;
        }
    }

    @Override
    public Object   appQueryAllFireByCondition(String startTime, String endTime, Integer page, Integer rows) {
        Long userId = JwtTokenUtils.getId();
        IPage<CommFireAlarm> iPage = new Page<>(page, rows);
        IPage<CommFireAlarm> pages = commFireAlarmDao.appQueryAllFireByCondition(iPage, userId, startTime, endTime);
        List<CommFireAlarm> records = pages.getRecords();
        if(CollUtil.isNotEmpty(records)){
            List<CommFireAlarm> commFireAlarms = this.setExtInfo(records);
            pages.setRecords(commFireAlarms);
        }
        PageData<Object> pageData = new PageData<>();
        pageData.setDatas(pages.getRecords());
        pageData.setCount((int) pages.getTotal());
        pageData.setCurrent((int) pages.getCurrent());
        pageData.setSize((int) pages.getSize());
        return pageData;
    }

    @Override
    public List<DistrictFireCountDTO> queryCountHistoryEmergencyFireByYear(String year) {
        Integer countNum = commFireAlarmDao.queryCountHistoryEmergencyFireByYear(year);
        List<Map<String, Object>> data = commFireAlarmDao.queryDistrictHistoryEmergencyFireCount(year);
        List<DistrictFireCountDTO> districtFireCountDTOS = new ArrayList<>(data.size());
        List<String> list = geoXzqhXiangDao.queryAllXiang();
        Set<String> set = new HashSet<>(list.size());
        set.addAll(list);
        data.forEach(e -> {
            String district = (String) e.get("district");
            set.remove(district);
            Long count = (Long) e.get("count");
            DistrictFireCountDTO districtFireCountDTO = new DistrictFireCountDTO();
            districtFireCountDTO.setCun(district);
            districtFireCountDTO.setNumber(count);
            districtFireCountDTO.setPercent(new BigDecimal(count).divide(new BigDecimal(countNum), 4, BigDecimal.ROUND_HALF_UP));
            districtFireCountDTOS.add(districtFireCountDTO);
        });
        set.forEach(e -> {
            DistrictFireCountDTO districtFireCountDTO = new DistrictFireCountDTO();
            districtFireCountDTO.setCun(e);
            districtFireCountDTO.setNumber(0L);
            districtFireCountDTO.setPercent(new BigDecimal(0));
            districtFireCountDTOS.add(districtFireCountDTO);
        });
        return districtFireCountDTOS;
    }


//    @Override
//    public List<CommFireAlarm> queryUnReadReportFire(Long userId) {
//        List<CommFireAlarm> list = new ArrayList<>();
//        SysUserDetailVo sysUserVo = userInfoService.getUserInfo(userId);
//        if (sysUserVo != null) {
//            String districtCode = sysUserVo.getDeptRegionCode();
//            //根据用户查询所有已读火情id
//            List<Long> hasReadFireMsgIds = webSocketPushMsgLogService.queryHasReadMsg(1, userId);
//            if (hasReadFireMsgIds != null && districtCode != null) {
//                int length = districtCode.length();
//                List<String> fireIds = businessTableDao.queryReportFireByDistrictCode(districtCode, String.valueOf(length));
//                if (fireIds != null) {
//                    fireIds.forEach(e -> {
//                        CommFireAlarm commFireAlarm = this.querySendFireById(Long.parseLong(e));
//                        if (commFireAlarm != null && !hasReadFireMsgIds.contains(Long.parseLong(e))) {
//                            list.add(commFireAlarm);
//                        }
//                    });
//                }
//            }
//        }
//        List<CommFireAlarm> commFireAlarms = list.stream().sorted(Comparator.comparing(CommFireAlarm::getFindTime).reversed()).collect(Collectors.toList());
//        return this.setExtInfo(commFireAlarms);
//    }

    @Override
    public List<CommFireAlarm> queryUnReadCurrentLevelFire(Long userId) {
        List<CommFireAlarm> list = new ArrayList<>();
        MicroSysUserAllInfoVo sysUserVo = userInfoService.getUserInfo(userId);
        if (sysUserVo != null) {
            String districtCode = sysUserVo.getAreaCode();
            int length = districtCode.length();
            //根据用户查询所有已读火情id
            List<Long> hasReadFireMsgIds = webSocketPushMsgLogService.queryHasReadMsg(1, userId);
            List<String> fireIds;
//            if (excludeDistrict.equals(districtCode)) {
            if (fireExcludeProp.getExcludeDistrict().contains(districtCode)) {
                //excludeDistrict 推送所有区域火情
                fireIds = businessTableDao.queryAllReportFire();
            } else {
                //分区域推送火情
//                fireIds = businessTableDao.queryCurrentLevelFireByDistrictCode(districtCode, String.valueOf(length));
                //查询当前用户行政级别及以下的火情信息
                if(StrUtil.isNotEmpty(districtCode) && districtCode.length() > 9){
                    districtCode=StrUtil.sub(districtCode,0,9);
                }
                fireIds = businessTableDao.queryCurrentAndHighLevelFireByDistrictCode(districtCode);
            }
            if (fireIds != null) {
                List<Long> collect = fireIds.stream().map(Long::parseLong).collect(Collectors.toList());
                collect.removeAll(hasReadFireMsgIds);
                if (CollectionUtil.isNotEmpty(collect)) {
                    list = commFireAlarmDao.selectUnReadFire(collect);
                }
            }
        }
        List<CommFireAlarm> commFireAlarms = list.stream().sorted(Comparator.comparing(CommFireAlarm::getFindTime).reversed()).collect(Collectors.toList());
        return this.setExtInfo(commFireAlarms);
    }

    @Override
    public boolean queryHasUnReadReportFire(Long userId) {
        MicroSysUserAllInfoVo sysUserVo = userInfoService.getUserInfo(userId);
        if (sysUserVo != null) {
            String districtCode = sysUserVo.getAreaCode();
            //根据用户查询所有已读火情id
            List<Long> hasReadFireMsgIds = webSocketPushMsgLogService.queryHasReadMsg(1, userId);
            if (hasReadFireMsgIds != null && districtCode != null) {
                int length = districtCode.length();
//                List<String> fireIds = businessTableDao.queryReportFireByDistrictCode(districtCode, String.valueOf(length));
//                if (fireIds != null) {
//                    for (String fireId : fireIds) {
//                        CommFireAlarm commFireAlarm = this.querySendFireById(Long.parseLong(fireId));
//                        if (commFireAlarm != null && !hasReadFireMsgIds.contains(Long.parseLong(fireId))) {
//                            return true;
//                        }
//                    }
//                }
            }
        }
        return false;
    }

    @Override
    public boolean queryHasUnReadCurrentLevelFire(Long userId) {
        MicroSysUserAllInfoVo sysUserVo = userInfoService.getUserInfo(userId);
        if (sysUserVo != null) {
            String districtCode = sysUserVo.getAreaCode();
            int length = districtCode.length();
            //根据用户查询所有已读火情id
            List<Long> hasReadFireMsgIds = webSocketPushMsgLogService.queryHasReadMsg(1, userId);
            List<String> fireIds=new ArrayList<>();
//            if (fireExcludeProp.getExcludeDistrict().contains(districtCode)) {
//                //excludeDistrict 推送所有区域火情
//                fireIds = businessTableDao.queryAllReportFire();
//            } else {
//                //分区域推送火情
////                fireIds = businessTableDao.queryCurrentLevelFireByDistrictCode(districtCode, String.valueOf(length));
//                //查询当前用户行政级别及以下的火情信息
//                fireIds = businessTableDao.queryCurrentAndHighLevelFireByDistrictCode(districtCode);
//            }
//            if (fireIds != null) {
//                for (String fireId : fireIds) {
//                    CommFireAlarm commFireAlarm = this.querySendFireById(Long.parseLong(fireId));
//                    if (commFireAlarm != null && !hasReadFireMsgIds.contains(Long.parseLong(fireId))) {
//                        return true;
//                    }
//                }
          //  }
        }
        return false;
    }

    @Override
    public LongitudeAndLatitudeDTO queryLongitudeAndLatitude(Long fireId) {
        return commFireAlarmDao.queryLongitudeAndLatitude(fireId);
    }

//    @Override
//    public  LongitudeAndLatitudeDTO queryLongitudeAndLatitude(Long fireId) {
//        return commFireAlarmDao.queryLongitudeAndLatitude(fireId);
//    }

    @Override
    public Object queryCameraFindFire(Integer page, Integer rows, Integer hasJudgment, String startTime, String endTime, String districtCode) {
        if (page != null && rows != null) {
            IPage<CommFireAlarm> iPage = new Page<>(page, rows);
            IPage<CommFireAlarm> pages = commFireAlarmDao.queryCameraFindFire(iPage, hasJudgment, startTime, endTime, districtCode);
            List<CommFireAlarm> records = pages.getRecords();
            List<CommFireAlarm> commFireAlarms = this.setExtInfo(records);
            pages.setRecords(commFireAlarms);
            PageData<Object> pageData = new PageData<>();
            pageData.setDatas(pages.getRecords());
            pageData.setCount((int) pages.getTotal());
            pageData.setCurrent((int) pages.getCurrent());
            pageData.setSize((int) pages.getSize());
            return pageData;
        } else {
            List<CommFireAlarm> commFireAlarms = commFireAlarmDao.queryCameraFindFireNoPage(hasJudgment, startTime, endTime, districtCode);
            this.setExtInfo(commFireAlarms);
            return commFireAlarms;
        }
    }

    @Override
    public FireCountDTO queryFireCount(String flag, String districtCode) {
        Date endTime = new Date();
        Date startTime = new Date();
        if ("day".equals(flag)) {
            startTime = TimeUtils.getCurrentDayZeroTime();
        } else if ("month".equals(flag)) {
            startTime = TimeUtils.getCurrentMonthZeroTime();
        } else if ("year".equals(flag)) {
            startTime = TimeUtils.getCurrentYearZeroTime();
        }

        Long countNum = commFireAlarmDao.queryFireCountByFlag(startTime, endTime);
        List<Map<String, Object>> data = commFireAlarmDao.queryFireCountByFlagAndSource(startTime, endTime);
        FireCountDTO fireCountDTO = new FireCountDTO();
        List<WarnFireCountDTO> warnFireCountDTOS = new ArrayList<>(data.size());
        data.forEach(e -> {
            String name = (String) e.get("name");
            Long count = (Long) e.get("count");
            WarnFireCountDTO warnFireCountDTO = new WarnFireCountDTO();
            warnFireCountDTO.setSource(name);
            warnFireCountDTO.setNumber(count);
            warnFireCountDTO.setPercent(new BigDecimal(count).divide(new BigDecimal(countNum), 4, BigDecimal.ROUND_HALF_UP));
            warnFireCountDTOS.add(warnFireCountDTO);
        });
        fireCountDTO.setWarnFireCountDTOS(warnFireCountDTOS);
        VerifyFireCountDTO verifyFireCountDTO = new VerifyFireCountDTO();
        Long realFireCount = commFireAlarmDao.queryRealFireCount(startTime, endTime);
        Long fakeFireCount = commFireAlarmDao.queryFakeFireCount(startTime, endTime);
        Long fireCount = realFireCount + fakeFireCount;
        verifyFireCountDTO.setRealNumber(realFireCount);
        verifyFireCountDTO.setFakeNumber(fakeFireCount);
        if (fakeFireCount != 0) {
            verifyFireCountDTO.setFakeFirePercent(new BigDecimal(fakeFireCount).divide(new BigDecimal(fireCount), 4, BigDecimal.ROUND_HALF_UP));
        } else {
            verifyFireCountDTO.setFakeFirePercent(new BigDecimal("0"));
        }
        fireCountDTO.setVerifyFireCountDTO(verifyFireCountDTO);
        return fireCountDTO;
    }

    @Override
    public List<VerifyCameraCountDTO> queryCountCameraFindFire() {
        List<VerifyCameraCountDTO> list = new ArrayList<>();
        Date endTime = new Date();
        Date startTime = TimeUtils.getCurrentDayZeroTime();
        Long count = commFireAlarmDao.queryCountAllCameraFindFire(startTime, endTime);
        Long realCameraFindFire = commFireAlarmDao.queryCountRealCameraFindFire(startTime, endTime);
        Long suspectCameraFindFire = commFireAlarmDao.queryCountSuspectCameraFindFire(startTime, endTime);
        Long fakeCameraFindFire = commFireAlarmDao.queryCountFakeCameraFindFire(startTime, endTime);
        VerifyCameraCountDTO realVerifyCameraCountDTO = new VerifyCameraCountDTO();
        realVerifyCameraCountDTO.setNumber(realCameraFindFire);
        realVerifyCameraCountDTO.setStatus("1");
        if (realCameraFindFire != 0) {
            realVerifyCameraCountDTO.setPercent(new BigDecimal(realCameraFindFire).divide(new BigDecimal(count), 4, BigDecimal.ROUND_HALF_UP));
        } else {
            realVerifyCameraCountDTO.setPercent(new BigDecimal(0));
        }
        list.add(realVerifyCameraCountDTO);
        VerifyCameraCountDTO suspectVerifyCameraCountDTO = new VerifyCameraCountDTO();
        suspectVerifyCameraCountDTO.setNumber(suspectCameraFindFire);
        suspectVerifyCameraCountDTO.setStatus("2");
        if (suspectCameraFindFire != 0) {
            suspectVerifyCameraCountDTO.setPercent(new BigDecimal(suspectCameraFindFire).divide(new BigDecimal(count), 4, BigDecimal.ROUND_HALF_UP));
        } else {
            suspectVerifyCameraCountDTO.setPercent(new BigDecimal(0));
        }
        list.add(suspectVerifyCameraCountDTO);
        VerifyCameraCountDTO fakeVerifyCameraCountDTO = new VerifyCameraCountDTO();
        fakeVerifyCameraCountDTO.setNumber(fakeCameraFindFire);
        fakeVerifyCameraCountDTO.setStatus("3");
        if (fakeCameraFindFire != 0) {
            fakeVerifyCameraCountDTO.setPercent(new BigDecimal(fakeCameraFindFire).divide(new BigDecimal(count), 4, BigDecimal.ROUND_HALF_UP));
        } else {
            fakeVerifyCameraCountDTO.setPercent(new BigDecimal(0));
        }
        list.add(fakeVerifyCameraCountDTO);
        return list;
    }

    @Override
    public List<DistrictFireCountDTO> queryFireCountByDistrict(String flag, String districtCode) {
        Date endTime = new Date();
        Date startTime = new Date();
        if ("day".equals(flag)) {
            startTime = TimeUtils.getCurrentDayZeroTime();
        } else if ("month".equals(flag)) {
            startTime = TimeUtils.getCurrentMonthZeroTime();
        } else if ("year".equals(flag)) {
            startTime = TimeUtils.getCurrentYearZeroTime();
        }

        List<DistrictFireCountDTO> districtFireCountDTOS = new ArrayList<>();
        if (StrUtil.isNotEmpty(districtCode) && districtCode.length() == 9) {
            List<Map<String, Object>> data3 = commFireAlarmDao.queryFireCountByDistrictCode(null, districtCode,
                    DateUtil.format(startTime, DatePattern.NORM_DATETIME_PATTERN),
                    DateUtil.format(endTime, DatePattern.NORM_DATETIME_PATTERN), null, null, null);
//                List<DistrictFireCountDTO> districtFireCountDTOS = new ArrayList<>(data3.size());
            List<String> list = geoXzqhCunDao.queryAllCunByDistrictCode(districtCode);
            for (String e : list) {
                DistrictFireCountDTO districtFireCountDTO = new DistrictFireCountDTO();
                districtFireCountDTO.setCun(e);
                districtFireCountDTO.setNumber(0L);
                districtFireCountDTO.setPercent(new BigDecimal(0));
                districtFireCountDTOS.add(districtFireCountDTO);
            }
            data3.forEach(e -> {
                String district = MapUtil.getStr(e, "district");
                int index = list.indexOf(district);
                Long count = MapUtil.getLong(e, "count");

                DistrictFireCountDTO districtFireCountDTO = new DistrictFireCountDTO();
                districtFireCountDTO.setCun(district);
                districtFireCountDTO.setNumber(count);
                districtFireCountDTOS.set(index, districtFireCountDTO);
            });
        } else if (StrUtil.isNotEmpty(districtCode) && districtCode.length() == 6) {
            List<Map<String, Object>> data3 = commFireAlarmDao.queryFireCountByDistrictCode1(null, districtCode,
                    DateUtil.format(startTime, DatePattern.NORM_DATETIME_PATTERN),
                    DateUtil.format(endTime, DatePattern.NORM_DATETIME_PATTERN), null, null, null);
//                List<DistrictFireCountDTO> districtFireCountDTOS = new ArrayList<>(data3.size());
            List<String> list = geoXzqhCunDao.queryAllXiangByDistrictCode(districtCode);
            for (String e : list) {
                DistrictFireCountDTO districtFireCountDTO = new DistrictFireCountDTO();
                districtFireCountDTO.setCun(e);
                districtFireCountDTO.setNumber(0L);
                districtFireCountDTO.setPercent(new BigDecimal(0));
                districtFireCountDTOS.add(districtFireCountDTO);
            }
            data3.forEach(e -> {
                String district = MapUtil.getStr(e, "district");
                int index = list.indexOf(district);
                Long count = MapUtil.getLong(e, "count");
                DistrictFireCountDTO districtFireCountDTO = new DistrictFireCountDTO();
                districtFireCountDTO.setCun(district);
                districtFireCountDTO.setNumber(count);
                districtFireCountDTOS.set(index, districtFireCountDTO);
            });
        } else if (StrUtil.isNotEmpty(districtCode) && districtCode.length() == 4) {
            List<Map<String, Object>> data3 = commFireAlarmDao.queryFireCountByDistrictCode2(null, districtCode,
                    DateUtil.format(startTime, DatePattern.NORM_DATETIME_PATTERN),
                    DateUtil.format(endTime, DatePattern.NORM_DATETIME_PATTERN), null, null, null);
//                List<DistrictFireCountDTO> districtFireCountDTOS = new ArrayList<>(data3.size());
            List<String> list = geoXzqhCunDao.queryAllXianByDistrictCode(districtCode);
//                Set<String> set = new HashSet<>(list.size());
//                set.addAll(list);
            for (String e : list) {
                DistrictFireCountDTO districtFireCountDTO = new DistrictFireCountDTO();
                districtFireCountDTO.setCun(e);
                districtFireCountDTO.setNumber(0L);
                districtFireCountDTO.setPercent(new BigDecimal(0));
                districtFireCountDTOS.add(districtFireCountDTO);
            }
            data3.forEach(e -> {
                String district = MapUtil.getStr(e, "district");
                int index = list.indexOf(district);
                Long count = MapUtil.getLong(e, "count");
                DistrictFireCountDTO districtFireCountDTO = new DistrictFireCountDTO();
                districtFireCountDTO.setCun(district);
                districtFireCountDTO.setNumber(count);
                districtFireCountDTOS.set(index, districtFireCountDTO);
            });
        } else {
            List<Map<String, Object>> data3 = commFireAlarmDao.queryDistrictFireCount(null, districtCode,
                    DateUtil.format(startTime, DatePattern.NORM_DATETIME_PATTERN),
                    DateUtil.format(endTime, DatePattern.NORM_DATETIME_PATTERN), null, null, null);
            List<String> list = geoXzqhXiangDao.queryAllXiang();
//                Set<String> set = new HashSet<>(list.size());
//                set.addAll(list);
            list.forEach(e -> {
                DistrictFireCountDTO districtFireCountDTO = new DistrictFireCountDTO();
                districtFireCountDTO.setCun(e);
                districtFireCountDTO.setNumber(0L);
                districtFireCountDTO.setPercent(new BigDecimal(0));
                districtFireCountDTOS.add(districtFireCountDTO);
            });
            data3.forEach(e -> {
                String district = MapUtil.getStr(e, "district");
                int index = list.indexOf(district);
                Long count = MapUtil.getLong(e, "count");
                DistrictFireCountDTO districtFireCountDTO = new DistrictFireCountDTO();
                districtFireCountDTO.setCun(district);
                districtFireCountDTO.setNumber(count);
                districtFireCountDTOS.set(index, districtFireCountDTO);
            });
        }
        return districtFireCountDTOS;
    }

    @Override
    public List<CommFireAlarm> queryFireDetailByCondition(String flag, String districtName, String districtCode,String fireLevel) {
       // String districtCode = "JwtTokenUtils.getVillageDistrictCode()";
        Date endTime = new Date();
        Date startTime = new Date();
        if ("day".equals(flag)) {
            startTime = TimeUtils.getCurrentDayZeroTime();
        } else if ("month".equals(flag)) {
            startTime = TimeUtils.getCurrentMonthZeroTime();
        } else if ("year".equals(flag)) {
            startTime = TimeUtils.getCurrentYearZeroTime();
        } else if (flag == null || "".equals(flag)) {
            startTime = null;
            endTime = null;
        }
        String code = null;
        if (!"".equals(districtName) && StrUtil.isNotEmpty(districtCode)) {
            if(districtCode.length() < 9){
                code = geoXzqhXiangDao.queryCodeByName(districtName);
            }else {
                code = geoXzqhXiangDao.queryCunCodeByXiangName(districtName);
            }
        }
        List<CommFireAlarm> list = commFireAlarmDao.queryFireDetailByCondition(startTime, endTime, code, fireLevel);
        this.setExtInfo(list);
        return list;
    }

    @Override
    public List<CommFireAlarm> queryHistoryFireDetailByCondition(String flag, String districtName, String fireLevel) {
        String districtCode = "JwtTokenUtils.getVillageDistrictCode()";
        Date endTime = new Date();
        Date startTime = new Date();
        if ("day".equals(flag)) {
            startTime = TimeUtils.getCurrentDayZeroTime();
        } else if ("month".equals(flag)) {
            startTime = TimeUtils.getCurrentMonthZeroTime();
        } else if ("year".equals(flag)) {
            startTime = TimeUtils.getCurrentYearZeroTime();
        } else if (flag == null || "".equals(flag)) {
            startTime = null;
            endTime = null;
        }
        String code = null;
        if (!"".equals(districtName) && StrUtil.isNotEmpty(districtCode)) {
            if(districtCode.length() < 9){
                code = geoXzqhXiangDao.queryCodeByName(districtName);
            }else {
                code = geoXzqhXiangDao.queryCunCodeByXiangName(districtName);
            }
        }
        if(StrUtil.isEmpty(districtName)){
            code="JwtTokenUtils.getVillageDistrictCode()";
        }
        List<CommFireAlarm> list = commFireAlarmDao.queryHistoryFireDetailByCondition(startTime, endTime, code, fireLevel);
        this.setExtInfo(list);
        return list;
    }

    @Override
    public Map queryAllFireStatusCount(String districtCode) {
        Map map = new HashMap<String, Long>();
        //初始数量0
        map.put("1", 0);
        map.put("2", 0);
        map.put("3", 0);
        map.put("4", 0);
        map.put("5", 0);
        map.put("6", 0);
        Date startTime = TimeUtils.getCurrentDayZeroTime();
        Date endTime = new Date();
        Long todayWarning = commFireAlarmDao.queryTodayFireCount(startTime, endTime, districtCode);
        map.put("7", todayWarning);
        List<Map<String, Object>> list = commFireAlarmDao.queryAllFireStatusCount(districtCode);
        list.forEach(e -> {
            String status = (String) e.get("status");
            Long count = (Long) e.get("count");
            map.put(status, count);
        });
        return map;
    }

    @Override
    public void verifyCameraFindSameFire(Long cameraId, double lit, double lat) {
        if (lit == 0L || lat == 0L) {
            throw new ForestBaseException("发现火情位置错误,经纬度为0!");
        }
        List<CommFireAlarm> list = commFireAlarmDao.queryCameraFindSameFire(cameraId, TimeUtils.getCurrentDayZeroTime(), new Date());
        List<CommFireAlarm> sameFire = list.stream().filter(
                e -> {
                    double distanceMeter = GeoUtils.GetDistanceTwo(lit, lat, Double.parseDouble(e.getLongitude()), Double.parseDouble(e.getLatitude()));
                    return distanceMeter < Double.parseDouble(cameraLimitDistance);
                }
        ).collect(Collectors.toList());
        if (!sameFire.isEmpty()) {
            throw new ForestBaseException("该火情已有上报记录!");
        }
    }

    @Override
    public List<Map> queryFireCountVO(String  districtCode) {

//        List<String> fireIdByCurrentUserRole = findFireIdByCurrentUserRole(fireCountDTO.getIsWatchman(),
//                fireCountDTO.getDistrictCode(),null);

        if (StringUtils.isNotBlank(districtCode)){
            districtCode=districtCode+"%";
        }
        List<Map> mapList = commFireAlarmDao.queryFireCountVO(districtCode);
        return mapList;
    }



    @Override
    public List<Map> fireSimpListByViewSearch(FireSimpListByViewSearchDTO dto) {
//        List<String> fireIdByCurrentUserRole = findFireIdByCurrentUserRole(dto.getIsWatchman(),
//                dto.getDistrictCode(),null);
        Integer rank = setRank(dto);
        List<String> result = new LinkedList<>();
        setDTO(dto, result);
        ViewSearchDTO viewSearchDTO = getViewSearchDTO(result);
        if (StringUtils.isNotBlank(dto.getDistrictCode())){
            dto.setDistrictCode(dto.getDistrictCode()+"%");
        }
        List<Map> mapList = commFireAlarmDao.fireSimpListByViewSearch(rank, viewSearchDTO);
        extracted(mapList);
        mapList.forEach(map -> map.put("category", "1"));
        mapList.forEach(map -> map.put("categoryName", "火点"));
        return mapList;
    }

    //地图资源统计显示
    @Override
    @Cacheable(value = "firecommand:fire:fireResourceSimpListByViewSearch", depict = "根据火情id查询火情基本信息(火情基本信息查询)", cacheMode = CacheMode.SECOND, secondaryCache = @SecondaryCache(expireTime = 300, preloadTime = 2, forceRefresh = true, timeUnit = TimeUnit.SECONDS))
    public List<Map> fireResourceSimpListByViewSearch(FireSimpListByViewSearchDTO dto) {
        List<Map> resultMap = new ArrayList<>();
        List<Map> mapList = new ArrayList<>();
        List<PlatTableVO> platTableVOList;
        Integer rank = setRank(dto);
        List<String> result = new LinkedList<>();
        setDTO(dto, result);

        ViewSearchDTO viewSearchDTO = getViewSearchDTO(result);
        if (StringUtils.isNotBlank(dto.getDistrictCode())) {
            viewSearchDTO.setDistrictCode(dto.getDistrictCode() + "%");
        }
        viewSearchDTO.setStatus(dto.getStatus() != null ? dto.getStatus().toString() : null);
        viewSearchDTO.setStatusList(dto.getStatusList());
        viewSearchDTO.setResourceName(dto.getResourceName());
        //查询资源对应的表
//        DataReturn allTableData = disposeFeignClient.selectAllTable(null);
//        if (!ResultCode.SUCCESS.getCode().equals(allTableData.getCode())
//                && !FireConstant.ALARMS_SUCCESS_CODE.equals(allTableData.getCode())) {
//            throw new ForestBaseException(allTableData.getErrorMsg());
//        }


//        List<Map> otherResource = new ArrayList<>();
//        List<Map> cameraResource = new ArrayList<>();
        List<Map> fireResource = new ArrayList<>();

        //查询资源
       // platTableVOList = JSON.parseArray(JSON.toJSONString(allTableData.getData()), PlatTableVO.class);
        if (dto.getCategory() == null) {

        }
        if (dto.getCategory().contains("1")) {
            //单独查询火点
            fireResource = getFireResource(dto, mapList, rank, result, viewSearchDTO);
        }
     //   if (dto.getCategory().contains("2")) {
            //单独查询视频
       //     String type=null;
        //    if (dto.getType()!=null){
         //       type=String.valueOf(dto.getType());
      //      }
         //   cameraResource = getCameraResource(platTableVOList, rank, viewSearchDTO,type);
     //   }
    //    if (dto.getCategory().contains("3")) {
            //单独查询动态资源
          //  otherResource = getOtherResource(platTableVOList, rank, viewSearchDTO);
    //    }
//        resultMap.addAll(otherResource);
//        resultMap.addAll(cameraResource);
        resultMap.addAll(fireResource);
        return resultMap;
    }


    @Override
    public List<ResourceSimpLevelMinVO> fireListBySearchLevelMin(FireSimpListByViewSearchDTO dto) {
//        List<String> fireIdByCurrentUserRole = findFireIdByCurrentUserRole(dto.getIsWatchman(),
//                dto.getDistrictCode(),null);
        if (StringUtils.isNotBlank(dto.getDistrictCode())){
            dto.setDistrictCode(dto.getDistrictCode()+"%");
        }
        List<String> result = new LinkedList<>();
        setDTO(dto, result);
        ViewSearchDTO viewSearchDTO = getViewSearchDTO(result);
        List<ResourceSimpLevelMinVO> fireSimpVOS = commFireAlarmDao.fireListBySearchLevelMin(viewSearchDTO);
        for (ResourceSimpLevelMinVO resourceSimpLevelMinVO : fireSimpVOS) {
            resourceSimpLevelMinVO.setCategory(1);
            resourceSimpLevelMinVO.setCategoryName("火点");
            resourceSimpLevelMinVO.setResourceName("火点");
        }
        return fireSimpVOS;
    }

    @Override
    public List<ResourceSimpLevelMinVO> fireListBySearchResourceLevelMin(FireSimpListByViewSearchDTO dto) {
        List<ResourceSimpLevelMinVO> resultList = new ArrayList<>();
        List<String> result = new LinkedList<>();
        setDTO(dto, result);
        ViewSearchDTO viewSearchDTO = getViewSearchDTO(result);
        Integer rank = setRank(dto);
        if (StringUtils.isNotBlank(dto.getDistrictCode())) {
            viewSearchDTO.setDistrictCode(dto.getDistrictCode() + "%");
        }
        viewSearchDTO.setResourceName(dto.getResourceName());
        //查询资源表(包括视频，动态资源)
        List<PlatTableVO> platTableVOList;

        List<ResourceSimpLevelMinVO> fireListBySearchLevelMin = new ArrayList<>();
//        List<ResourceSimpLevelMinVO> cameraSimpList = new ArrayList<>();
//        List<ResourceSimpLevelMinVO> resource = new ArrayList<>();
        //查询资源对应的表
//        DataReturn allTableData = disposeFeignClient.selectAllTable(null);
//        if (!ResultCode.SUCCESS.getCode().equals(allTableData.getCode())
//                && !FireConstant.ALARMS_SUCCESS_CODE.equals(allTableData.getCode())) {
//            throw new ForestBaseException(allTableData.getErrorMsg());
//        }
        //查询资源
       // platTableVOList = JSON.parseArray(JSON.toJSONString(allTableData.getData()), PlatTableVO.class);
        if (dto.getCategory() == null) {

        }
        if (dto.getCategory().contains("1")) {
            //火点
            fireListBySearchLevelMin = getFireListBySearchLevelMin(dto);
        }
//        if (dto.getCategory().contains("2")) {
//            //视频
//            //单独查询视频
//            String type=null;
//            if (dto.getType()!=null){
//                type=String.valueOf(dto.getType());
//            }
//            cameraSimpList = getCameraSimpList(viewSearchDTO, platTableVOList, rank,type);
//        }
//        if (dto.getCategory().contains("3")) {
//            //资源\
//            resource = getResourceSimpLevelMinVOS(viewSearchDTO, platTableVOList, rank);
//        }
        resultList.addAll(fireListBySearchLevelMin);
//        resultList.addAll(cameraSimpList);
//        resultList.addAll(resource);

        return resultList;
    }



    private void setDTO(FireSimpListByViewSearchDTO dto, List<String> result) {
        if (StringUtils.isNotBlank(dto.getLonAndLanStr())) {
            String[] split = dto.getLonAndLanStr().split(",");

            for (int i = 0; i < split.length; i++) {
                String[] s1 = split[i].split(" ");
                for (int i1 = 0; i1 < s1.length; i1++) {
                    result.add(s1[i1]);
                }
            }
        }
    }

    @NotNull
    private ViewSearchDTO getViewSearchDTO(List<String> result) {
        ViewSearchDTO viewSearchDTO = new ViewSearchDTO();
        viewSearchDTO.setLon1(result.get(0));
        viewSearchDTO.setLon2(result.get(2));
        viewSearchDTO.setLon3(result.get(4));
        viewSearchDTO.setLon4(result.get(6));
        viewSearchDTO.setLon5(result.get(8));

        viewSearchDTO.setLan1(result.get(1));
        viewSearchDTO.setLan2(result.get(3));
        viewSearchDTO.setLan3(result.get(5));
        viewSearchDTO.setLan4(result.get(7));
        viewSearchDTO.setLan5(result.get(9));
        return viewSearchDTO;
    }


    private List<Map> getFireResource(FireSimpListByViewSearchDTO dto, List<Map> mapList, Integer rank, List<String> result, ViewSearchDTO viewSearchDTO) {
//        List<String> fireIdByCurrentUserRole = findFireIdByCurrentUserRole(dto.getIsWatchman(), dto.getDistrictCode(),null);
        setDTO(dto, result);
        List<Map> fireResource = commFireAlarmDao.fireSimpListByViewSearch(rank, viewSearchDTO);
        fireResource.forEach(map -> map.put("category", "1"));
        fireResource.forEach(map -> map.put("categoryName", "火点"));
        fireResource.forEach(map -> map.put("resourceName", "火点"));
//        fireResource.forEach(map -> map.put("status", viewSearchDTO.getStatus()));
//        fireResource.forEach(
//                map -> map.put("statusName", FireStatusStatus.code2Str(Integer.parseInt(viewSearchDTO.getStatus()))));
        extracted(fireResource);
        return fireResource;
    }

//    private List<Map> getCameraResource(List<PlatTableVO> platTableVOList, Integer rank, ViewSearchDTO viewSearchDTO,String type) {
//        //查询视频的
//        List<Map> resultMap = new ArrayList<>();
//        platTableVOList = platTableVOList.stream().filter(platTableVO -> platTableVO.getTableName().contains("camera")).collect(Collectors.toList());
//        for (PlatTableVO platTableVO : platTableVOList) {
//
//            List<Map> resourceMap = fireQueryDao.fireCameraSimpListByViewSearch(rank, platTableVO.getTableName(), viewSearchDTO,type);
//            resourceMap.forEach(map -> map.put("category", "2"));
//            resourceMap.forEach(map -> map.put("categoryName", "视频"));
//            if (StringUtils.isNotBlank(type)){
//                resourceMap.forEach(map -> map.put("monitoringType", type));
//                resourceMap.forEach(map -> map.put("monitoringTypeName", type.equals("1")?"防火监控":"卡口监控"));
//            }else {
//                resourceMap.forEach(map -> map.put("typeCount", fireQueryDao.findCameraType(map.get("code").toString())));
//            }
//            // resourceMap.forEach(map -> map.put("monitoringType", type));
//            resourceMap.forEach(map -> map.put("resourceName", platTableVO.getName()));
//            extracted(resourceMap);
//            resultMap.addAll(resourceMap);
//        }
//        return resultMap;
//    }

//    private List<Map> getOtherResource(List<PlatTableVO> platTableVOList, Integer rank, ViewSearchDTO viewSearchDTO) {
//        List<String> tableNameList = new ArrayList<>();
//        if (StringUtils.isNotBlank(viewSearchDTO.getResourceName())) {
//            tableNameList = CommonUtil.convertStringList(viewSearchDTO.getResourceName());
//        }
//        //查询动态资源
//        List<Map> resultMap = new ArrayList<>();
////        if (StringUtils.isNotBlank(viewSearchDTO.getResourceName())){
////            platTableVOList = platTableVOList.stream().filter(platTableVO -> platTableVO.getTableName().contains(viewSearchDTO.getResourceName())).collect(Collectors.toList());
////        }else {
////            platTableVOList = platTableVOList.stream().filter(platTableVO -> !platTableVO.getTableName().contains("camera")).collect(Collectors.toList());
////        }
//        for (PlatTableVO platTableVO : platTableVOList) {
//            if (tableNameList.contains(platTableVO.getTableName())) {
//                List<Map> resourceMap = commFireAlarmDao.fireResourceSimpListByViewSearch(rank, platTableVO.getTableName(), viewSearchDTO);
//                resourceMap.forEach(map -> map.put("category", "3"));
//                resourceMap.forEach(map -> map.put("categoryName", "资源"));
//                resourceMap.forEach(map -> map.put("resourceName", platTableVO.getName()));
//                extracted(resourceMap);
//                resultMap.addAll(resourceMap);
//            }
//        }
//        return resultMap;
//    }


//    private List<ResourceSimpLevelMinVO> getCameraSimpList(ViewSearchDTO viewSearchDTO, List<PlatTableVO> platTableVOList, Integer rank,String type) {
//        platTableVOList = platTableVOList.stream().filter(platTableVO -> platTableVO.getTableName().contains("camera")).collect(Collectors.toList());
//        //查询视频点
//        List<ResourceSimpLevelMinVO> cameraSimpList = commFireAlarmDao.fireCameraSimpList(rank, viewSearchDTO,type);
//        for (ResourceSimpLevelMinVO resourceSimpLevelMinVO : cameraSimpList) {
//            resourceSimpLevelMinVO.setCategory(2);
//            resourceSimpLevelMinVO.setCategoryName("视频");
//            resourceSimpLevelMinVO.setResourceName("视频监控");
//        }
//        return cameraSimpList;
//    }


//    private List<ResourceSimpLevelMinVO> getResourceSimpLevelMinVOS(ViewSearchDTO viewSearchDTO, List<PlatTableVO> platTableVOList, Integer rank) {
//
//        List<String> tableNameList = new ArrayList<>();
//        if (StringUtils.isNotBlank(viewSearchDTO.getResourceName())) {
//            tableNameList = CommonUtil.convertStringList(viewSearchDTO.getResourceName());
//        }
//        List<ResourceSimpLevelMinVO> resource = new ArrayList<>();
////        if (StringUtils.isNotBlank(viewSearchDTO.getResourceName())&&!viewSearchDTO.getResourceName().contains("camera")){
////            platTableVOList = platTableVOList.stream().filter(platTableVO -> platTableVO.getTableName().contains(viewSearchDTO.getResourceName())).collect(Collectors.toList());
////        }else {
////            platTableVOList = platTableVOList.stream().filter(platTableVO -> !platTableVO.getTableName().contains("camera")).collect(Collectors.toList());
////        }
//        for (PlatTableVO platTableVO : platTableVOList) {
//            if (tableNameList.contains(platTableVO.getTableName())) {
//                List<ResourceSimpLevelMinVO> resourceSimpList = commFireAlarmDao.fireResourceSimpList(platTableVO.getTableName(), rank, viewSearchDTO);
//                for (ResourceSimpLevelMinVO resourceSimpLevelMinVO : resourceSimpList) {
//                    resourceSimpLevelMinVO.setCategory(3);
//                    //查询资源图标
//                    resourceSimpLevelMinVO.setTableId(platTableVO.getId());
//                    resourceSimpLevelMinVO.setIconImg(platTableVO.getIconImg());
//                    resourceSimpLevelMinVO.setCategoryName("资源");
//                    resourceSimpLevelMinVO.setResourceName(platTableVO.getName());
//                }
//                resource.addAll(resourceSimpList);
//            }
//        }
//        return resource;
//    }

    private List<ResourceSimpLevelMinVO> getFireListBySearchLevelMin(FireSimpListByViewSearchDTO dto) {
        FireSimpListByViewSearchDTO fireSimpListByViewSearchDTO = new FireSimpListByViewSearchDTO();
        fireSimpListByViewSearchDTO.setDistrictCode(dto.getDistrictCode());
        fireSimpListByViewSearchDTO.setLevel(dto.getLevel());
        fireSimpListByViewSearchDTO.setIsWatchman(dto.getIsWatchman());
        fireSimpListByViewSearchDTO.setCategory(dto.getCategory());
        fireSimpListByViewSearchDTO.setLonAndLanStr(dto.getLonAndLanStr());
        fireSimpListByViewSearchDTO.setStatus(dto.getStatus());
        List<ResourceSimpLevelMinVO> fireListBySearchLevelMin = fireListBySearchLevelMin(fireSimpListByViewSearchDTO);
        return fireListBySearchLevelMin;
    }


    private void extracted(List<Map> mapList) {
        for (Map map : mapList) {
            String code = null;
            if (ObjectUtil.isNotNull(map.get("code"))) {
                code = map.get("code").toString();
            }
            List<Map> xY=new ArrayList<>();
            if (code.length()==4) {
                xY = geoXzqhCunDao.queryShiXyByCode(code, code.length());
            }
            if (code.length()==6) {
                xY = geoXzqhCunDao.queryXyXianByCode(code, code.length());
            }
            if (code.length()==9) {
                xY = geoXzqhCunDao.queryXiangXyByCode(code, code.length());
            }
            if (xY != null && xY.size() > 0) {
                if (ObjectUtil.isNotNull(xY.get(0).get("longitude"))) {
                    map.put("longitude", xY.get(0).get("longitude").toString());
                }
                if (ObjectUtil.isNotNull(xY.get(0).get("latitude"))) {
                    map.put("latitude", xY.get(0).get("latitude").toString());
                }
                String districtName = geoXzqhCunDao.queryOneNameByCode(code, code.length());
                map.put("districtName", districtName);
            }
        }
    }


    @NotNull
    private Integer setRank(FireSimpListByViewSearchDTO dto) {
        Integer rank = 6;
        if (dto.getLevel() != null) {
            if (dto.getLevel() == 0) {
                rank = 4;
            }
            if (dto.getLevel() == 1) {
                rank = 6;
            }
            if (dto.getLevel() == 2) {
                rank = 9;
            }
            if (dto.getLevel() == 3) {
                rank = 9;
            }
        }
        return rank;
    }

    /*
     * 构建 fireTypes 查询 SQL
     * TODO：该参数是宜昌项目对接外部，外部需要这样区分
     * 重要火情数：fire_level in ('1','2','3','4')
     * 一般火情数（不是 重要火情、非火情、重复告警）：((fire_level in ('5') or fire_level is null) and (status != '6') and (origin_fire_id = 0))
     * 非火情：status = '6'
     * 重复告警数：origin_fire_id != 0
     */
    private String buildSqlForFireTypes(String fireTypesStr) {
        List<String> fireTypes;
        if (StrUtil.isNotEmpty(fireTypesStr)) {
            fireTypes = Arrays.asList(fireTypesStr.split(","));
        } else {
            return "and ( 1 = 1 ) ";
        }
        String fireType1 = fireTypes.contains("1") ? "1" : null;
        String fireType2 = fireTypes.contains("2") ? "2" : null;
        String fireType3 = fireTypes.contains("3") ? "3" : null;
        String fireType4 = fireTypes.contains("4") ? "4" : null;
        String sql1 = "(fire_level in ('1','2','3','4'))";
        String sql2 = "((fire_level in ('5') or fire_level is null) and (status != '6') and (origin_fire_id = 0))";
        String sql3 = "(status = '6')";
        String sql4 = "(origin_fire_id != 0)";
        String or = " or ";
        StringBuffer sql = new StringBuffer("and ( ");
        if (StrUtil.isNotEmpty(fireType1) && StrUtil.isEmpty(fireType2) && StrUtil.isEmpty(fireType3)
                && StrUtil.isEmpty(fireType4)) { //1
            sql.append(sql1);
        } else if (StrUtil.isNotEmpty(fireType1) && StrUtil.isNotEmpty(fireType2) && StrUtil.isEmpty(fireType3)
                && StrUtil.isEmpty(fireType4)) { //1 2
            sql.append(sql1).append(or).append(sql2);
        } else if (StrUtil.isNotEmpty(fireType1) && StrUtil.isEmpty(fireType2) && StrUtil.isNotEmpty(fireType3)
                && StrUtil.isEmpty(fireType4)) { //1 3
            sql.append(sql1).append(or).append(sql3);
        } else if (StrUtil.isNotEmpty(fireType1) && StrUtil.isEmpty(fireType2) && StrUtil.isEmpty(fireType3)
                && StrUtil.isNotEmpty(fireType4)) { //1 4
            sql.append(sql1).append(or).append(sql4);
        } else if (StrUtil.isNotEmpty(fireType1) && StrUtil.isNotEmpty(fireType2) && StrUtil.isNotEmpty(fireType3)
                && StrUtil.isEmpty(fireType4)) { //1 2 3
            sql.append(sql1).append(or).append(sql2)
                    .append(or).append(sql3);
        } else if (StrUtil.isNotEmpty(fireType1) && StrUtil.isNotEmpty(fireType2) && StrUtil.isEmpty(fireType3)
                && StrUtil.isNotEmpty(fireType4)) { //1 2 4
            sql.append(sql1).append(or).append(sql2)
                    .append(or).append(sql4);
        } else if (StrUtil.isNotEmpty(fireType1) && StrUtil.isEmpty(fireType2) && StrUtil.isNotEmpty(fireType3)
                && StrUtil.isNotEmpty(fireType4)) { //1 3 4
            sql.append(sql1).append(or).append(sql3)
                    .append(or).append(sql4);
        } else if (StrUtil.isNotEmpty(fireType1) && StrUtil.isEmpty(fireType2) && StrUtil.isNotEmpty(fireType3)
                && StrUtil.isNotEmpty(fireType4)) { //1 2 3 4
            sql.append(" 1 = 1");
        } else if (StrUtil.isEmpty(fireType1) && StrUtil.isNotEmpty(fireType2) && StrUtil.isEmpty(fireType3)
                && StrUtil.isEmpty(fireType4)) { //2
            sql.append(sql2);
        } else if (StrUtil.isEmpty(fireType1) && StrUtil.isNotEmpty(fireType2) && StrUtil.isNotEmpty(fireType3)
                && StrUtil.isEmpty(fireType4)) { //2 3
            sql.append(sql2).append(or).append(sql3);
        } else if (StrUtil.isEmpty(fireType1) && StrUtil.isNotEmpty(fireType2) && StrUtil.isEmpty(fireType3)
                && StrUtil.isNotEmpty(fireType4)) { //2 4
            sql.append(sql2).append(or).append(sql3);
        } else if (StrUtil.isEmpty(fireType1) && StrUtil.isNotEmpty(fireType2) && StrUtil.isNotEmpty(fireType3)
                && StrUtil.isNotEmpty(fireType4)) { //2 3 4
            sql.append(sql2).append(or).append(sql3).append(or).append(sql4);
        } else if (StrUtil.isEmpty(fireType1) && StrUtil.isEmpty(fireType2) && StrUtil.isNotEmpty(fireType3)
                && StrUtil.isEmpty(fireType4)) { //3
            sql.append(sql3);
        } else if (StrUtil.isEmpty(fireType1) && StrUtil.isEmpty(fireType2) && StrUtil.isNotEmpty(fireType3)
                && StrUtil.isNotEmpty(fireType4)) { //3 4
            sql.append(sql3).append(or).append(sql4);
        } else if (StrUtil.isEmpty(fireType1) && StrUtil.isEmpty(fireType2) && StrUtil.isEmpty(fireType3)
                && StrUtil.isNotEmpty(fireType4)) { //4
            sql.append(sql4);
        } else {
            sql.append(" 1 = 1");
        }
        sql.append(" )");
        return sql.toString();
    }

    @Override
    public PageData<List<CommFireAlarm>> queryAllFireByCondition(FireQueryListDTO fireQueryListDTO) {
        IPage<CommFireAlarm> appTaskStatusPage = new Page<>(fireQueryListDTO.getPage(), fireQueryListDTO.getRows());
        List<String> fireLevels = new ArrayList<>();
        if (StrUtil.isNotEmpty(fireQueryListDTO.getFireLevels())) {
            fireLevels = Arrays.asList(fireQueryListDTO.getFireLevels().split(","));
        }
        
        //构建 fireTypes 查询 SQL
        String sql = buildSqlForFireTypes(fireQueryListDTO.getFireTypes());

        IPage<CommFireAlarm> pages = commFireAlarmDao.queryAllFireByCondition(appTaskStatusPage,
                fireQueryListDTO.getStatus(), fireQueryListDTO.getStartTime(),
                fireQueryListDTO.getEndTime(), fireQueryListDTO.getDistrictCode(), fireQueryListDTO.getResource(),
                fireQueryListDTO.getIsEmergencyDrill(), fireQueryListDTO.getFireLevel(), fireLevels,
                fireQueryListDTO.getFireName(), sql);
        List<CommFireAlarm> records = pages.getRecords();
        List<CommFireAlarm> commFireAlarms = this.setExtInfo(records);
        pages.setRecords(commFireAlarms);
        PageData<List<CommFireAlarm>> pageData = new PageData<>();
        pageData.setDatas(pages.getRecords());
        pageData.setCount((int) pages.getTotal());
        pageData.setCurrent((int) pages.getCurrent());
        pageData.setSize((int) pages.getSize());
        return pageData;
    }

    @Override
    public Map<String, Object> queryCount(String districtCode) {
        //待接警
        int waitReceived = commFireAlarmDao.queryCount(districtCode, "1");

        Map<String, Object> result = new HashMap<>();
        result.put("waitReceived", waitReceived);
        return result;
    }

}
